﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Linq;
using System.ServiceModel.DomainServices.Client;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using NetBay.Core.BusinessEntities;
using NetBay.Core.BusinessEntities.Historic;
using NetBay.Core.BusinessEntities.Versioning;
using NetBay.Core.Encryption.Licensing;
using NetBay.Core.Silverlight.Log;
using NetBay.Core.Silverlight.Tools;
using Rio.Applications.Web.Services;
using Rio.Framework.Localisation;
using Rio.Framework.Pages.Context;
using Rio.Framework.Pages.CriteriaControls;
using Rio.Framework.Pages.Enums;
using Rio.Framework.Pages.Events;
using Rio.Framework.Pages.Helpers;
using Rio.Framework.Pages.Manager;
using Rio.Framework.Pages.Viewer;
using Telerik.Windows.Controls;
using Telerik.Windows.Controls.DragDrop;
using Rio.Framework.Pages.AppCode.Enums;
using NetBay.Core.BusinessEntities.Workflow;
using GalaSoft.MvvmLight.Messaging;
using Rio.Framework.Pages.ChildWindows;
using GalaSoft.MvvmLight.Command;
using Telerik.Windows.Controls.TreeView;
using DataItemTreeView = Rio.Framework.Pages.AppCode.Models.DataItemTreeView;
using DataItemTreeViewCollection = Rio.Framework.Pages.AppCode.Models.DataItemTreeViewCollection;
using Rio.Framework.Pages.AppCode.Events;
using System.Windows.Data;
using Rio.Framework.Pages.Extensions;
using System.Text.RegularExpressions;
using ListBoxItem = System.Windows.Controls.ListBoxItem;

namespace Rio.Framework.Pages.Controls
{
    public partial class FolderPage
    {
        #region Enums
        public enum SelectModeDocument
        {
            Thumbnail,
            Viewer,
            List
        }

        #endregion

        #region Fields


        #region Fields
        private SaveFileDialog dialog;
        #endregion

        #region Label for translation

        private string m_szUpdateValidation;
        private string m_szUpdateFailed;
        private string m_szMessageMandatoryField;
        private string m_szLabelUpdate;
        private string m_szOverwriteConfirmation;
        private string m_sLabelCantConsult;
        private string m_sLabelButtonModifyIndex;
        private string m_sLabelButtonSaveIndex;
        private string m_sLabelButtonManageFolderRights;
        private string m_szMsgDocumentInCheckout;

        #endregion

        private ObservableCollection<Document> _listDocument;
        private DataItemTreeView m_oCurrentSelectedItem;

        private ListVignetteSearch m_oListVignetteSearch;
        private UCViewer m_oViewerControl;
        private ListViewer m_oListViewer;

        private Organization _currentOrganization;
        private FolderType _currentFolderType;
        private Folder m_oCurrentFolder;
        private string m_szMsgNoUnicity = string.Empty;
        private string m_szMsgFolderExist = string.Empty;
        private Document m_oCurrentDocument;
        private ObservableCollection<Document> _selectedDocumentsFromThumbnails;
        public List<Document> m_oListSelectedDocumentFromItem;
        private bool m_bIsInit = true;
        private DataItemTreeView m_oPreviousSelectedItem;
        private int m_iActivePanel = 0;
        private int m_iCounterUpdateOk = 0;
        private int m_iCounterUpdateKO = 0;
        private SelectModeDocument DisplayMode;
        private SplashScreen m_oSplashScreen = new SplashScreen();
        private bool m_bCanModify = false;
        private bool m_bCanDelete = false;
        private bool m_bCanTrash;
        public event EventHandler DataHasChanged;
        private VersioningItem _currentVersion;

        private VersioningManager _versioningManager;
        private WorkflowManager _workflowManager;
        private FlowIndexPanel displayedFlowIndexPanel;

        private SolidColorBrush _radOutlookBarDocumentItemColorBackground;


        #endregion

        #region Properties

        public CommentChildWindow CommentChildWindow { get; private set; }

        /// <summary>
        /// Gets or sets the type of the consultation mode.
        /// </summary>
        /// <value>The type of the consultation mode.</value>
        public ConsultationModeType ConsultationModeType { get; set; }

        /// <summary>
        /// Gets or sets the app display mode.
        /// </summary>
        /// <value>The app display mode.</value>
        public AppDisplayMode AppDisplayMode { get; set; }

        /// <summary>
        /// Gets or sets the workflow manager.
        /// </summary>
        /// <value>The workflow manager.</value>
        public WorkflowManager WorkflowManager
        {
            get
            {
                return _workflowManager;
            }
            set
            {
                _workflowManager = value;
                OnPropertyChanged("WorkflowManager");
            }
        }

        /// <summary>
        /// Gets a value indicating whether this instance is workflow context.
        /// </summary>
        /// <value>
        /// <c>true</c> if this instance is workflow context; otherwise, <c>false</c>.
        /// </value>
        public bool IsWorkflowContext
        {
            get
            {
                return _workflowManager != null;
            }
        }

        /// <summary>
        /// Gets or sets the selected documents from thumbnails.
        /// </summary>
        /// <value>The selected documents from thumbnails.</value>
        public ObservableCollection<Document> SelectedDocumentsFromThumbnails
        {
            get
            {
                return _selectedDocumentsFromThumbnails;
            }
            set
            {
                _selectedDocumentsFromThumbnails = value;
                OnPropertyChanged("SelectedDocumentsFromThumbnails");

                if (WorkflowManager != null)
                {
                    WorkflowManager.SelectedDocuments = _selectedDocumentsFromThumbnails;

                    ManageWorkflowMenu();
                }
            }
        }

        public RelayCommand<bool> OpenCommentWindowCommand { get; set; }
        public RelayCommand OpenHistoricWindowCommand { get; set; }

        /// <summary>
        /// Gets or sets the make to major command.
        /// </summary>
        /// <value>The make to major command.</value>
        public RelayCommand<VersionInformations.VersionSelectedEventArgs> MakeToMajorCommand { get; set; }

        /// <summary>
        /// Gets or sets the make to major command.
        /// </summary>
        /// <value>The make to major command.</value>
        public RelayCommand<VersionInformations.VersionSelectedEventArgs> CheckOutCommand { get; set; }

        /// <summary>
        /// Gets or sets the version selected command.
        /// </summary>
        /// <value>The version selected command.</value>
        public RelayCommand<VersionInformations.VersionSelectedEventArgs> VersionSelectedCommand { get; set; }

        /// <summary>
        /// Gets or sets the add version command.
        /// </summary>
        /// <value>The add version command.</value>
        public RelayCommand<RoutedEventArgs> AddVersionCommand { get; set; }

        /// <summary>
        /// Gets or sets the document updating command.
        /// </summary>
        /// <value>The document updating command.</value>
        public RelayCommand<DocumentInformations.DocumentInformationEventArgs> DocumentUpdatingCommand { get; set; }

        /// <summary>
        /// Gets or sets the current organization.
        /// </summary>
        /// <value>The current organization.</value>
        public Organization CurrentOrganization
        {
            get
            {
                return _currentOrganization;
            }
            set
            {
                _currentOrganization = value;
                OnPropertyChanged("CurrentOrganization");
            }
        }

        /// <summary>
        /// Gets or sets the type of the current folder.
        /// </summary>
        /// <value>The type of the current folder.</value>
        public FolderType CurrentFolderType
        {
            get
            {
                return _currentFolderType;
            }
            set
            {
                _currentFolderType = value;
                OnPropertyChanged("CurrentFolderType");
            }
        }

        /// <summary>
        /// Gets or sets the current folder.
        /// </summary>
        /// <value>The current folder.</value>
        public Folder CurrentFolder
        {
            get
            {
                return m_oCurrentFolder;
            }
            set
            {
                m_oCurrentFolder = value;

                OnPropertyChanged("CurrentFolder");

                AddOrRefreshTrashItemInTreeView();
            }
        }

        /// <summary>
        /// Gets or sets the folder comment.
        /// </summary>
        /// <value>The folder comment.</value>
        public string FolderComment { get; set; }

        /// <summary>
        /// Get or Set the current document
        /// </summary>
        /// <value>The current document.</value>
        public Document CurrentDocument
        {
            get
            {
                return m_oCurrentDocument;
            }
            set
            {
                m_oCurrentDocument = value;

                OnPropertyChanged("CurrentDocument");
                InitDataDocument();

                if (WorkflowManager != null)
                {
                    WorkflowManager.SelectedDocuments = new ObservableCollection<Document> { m_oCurrentDocument };
                    ManageWorkflowMenu();
                }
            }
        }

        /// <summary>
        /// Get or set the current selected version 
        /// </summary>
        public VersioningItem CurrentSelectedVersion
        {
            get
            {
                return _currentVersion;
            }
            set
            {
                _currentVersion = value;
                OnPropertyChanged("CurrentSelectedVersion");

                ManageFolderInformations();
            }
        }

        /// <summary>
        /// Get the selected item
        /// </summary>
        public DataItemTreeView SelectedItem
        {
            get
            {
                if (TreeViewControlItems.CurrentSelectedItem != null)
                {
                    return TreeViewControlItems.CurrentSelectedItem;
                }
                return null;
            }
            set
            {
                TreeViewControlItems.CurrentSelectedItem = value;
            }
        }

        /// <summary>
        /// Get or Set the list of all documents 
        /// </summary>
        /// 
        public ObservableCollection<Document> ListDocument
        {
            get
            {
                return _listDocument;
            }
            set
            {
                _listDocument = value;
                OnPropertyChanged("ListDocument");
            }
        }
        
        /// <summary>
        /// Get and set the RadOutlookBarDocumentItem background color.
        /// </summary>
        public SolidColorBrush RadOutlookBarDocumentItemColorBackground
        {
            get
            {
                return _radOutlookBarDocumentItemColorBackground;
            }
            set
            {
                _radOutlookBarDocumentItemColorBackground = value;
                OnPropertyChanged("RadOutlookBarDocumentItemColorBackground");
            }
        }

        #endregion

        #region Events

        public event PasteCopyEventHandler DocumentCopiedOrCuted;
        private void OnDocumentCopiedOrCut(PasteCopyActionType Action, Folder SourceFolder)
        {
            if (DocumentCopiedOrCuted != null)
            {
                DocumentCopiedOrCuted(this, new PasteCopyEventArgs(Action, SourceFolder));
            }
        }

        public virtual void OnDataHasChanged()
        {
            if (DataHasChanged != null)
                DataHasChanged(this, EventArgs.Empty);
        }

        #endregion

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="FolderPage" /> class.
        /// </summary>
        /// <param name="P_oOrganization">The organization.</param>
        /// <param name="P_oFolderType">Type of the folder.</param>
        /// <param name="displayMode">The display mode.</param>
        private FolderPage(Organization P_oOrganization, FolderType P_oFolderType, AppDisplayMode displayMode = AppDisplayMode.Search)
        {
            InitializeComponent();

            Loaded += FolderPageLoaded;

            this.dialog = new SaveFileDialog();
            try
            {
                this.dialog.DefaultExt = ".txt";
                this.dialog.Filter = "All Files|*.*";
                this.dialog.FilterIndex = 1;
            }
            catch (Exception ex)
            {
                LoggerHelper.Send(this.GetType().Name, "CheckOutClick EXCEPTION : " + Environment.NewLine + ex.Message);
            }

            AppDisplayMode = displayMode;
            m_oSplashScreen.Show();
            ModalControls.ModalDialogController.Launch(m_oSplashScreen);

            // Disable Index panel and Document info panel if user can't modify folder
            m_bCanModify = GlobalWebContext.GetUserCanModify(P_oFolderType);
            buttonUpdateIndex.Visibility = (m_bCanModify) ? Visibility.Visible : Visibility.Collapsed;
            buttonUpdateDocumentItem.Visibility = (m_bCanModify) ? Visibility.Visible : Visibility.Collapsed;
            m_bCanDelete = GlobalWebContext.GetUserCanDelete(P_oFolderType);
            m_bCanTrash = GlobalWebContext.GetUserCanTrash(P_oFolderType);
            DocumentInfo.IsEnabled = m_bCanModify;

            // Collapse ManageFolderRight button if user isn't an administrator
            if (GlobalWebContext.GetIsAdministrator(P_oFolderType))
            {
                ManageFolderRightButton.Visibility = System.Windows.Visibility.Visible;
            }
            else
            {
                ManageFolderRightButton.Visibility = System.Windows.Visibility.Collapsed;
            }

            // Loads Labels 
            InitLabel();

            CurrentOrganization = P_oOrganization;
            CurrentFolderType = P_oFolderType;

            //Loads items
            InitItems();

            //Versioning manager 
            _versioningManager = new VersioningManager();
            _versioningManager.VersionCreated += versioningManager_VersionCreated;
            _versioningManager.CreationError += versioningManager_CreationError;

            InitCommand();
        }

        private void FolderPageLoaded(object sender, RoutedEventArgs e)
        {
            OpenCommentWindow(true);
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="FolderPage" /> class.
        /// </summary>
        /// <param name="P_oOrganization">The organization.</param>
        /// <param name="P_oFolderType">Type of the folder.</param>
        /// <param name="P_oDocument">The document.</param>
        /// <param name="displayMode">The display mode.</param>
        public FolderPage(Organization P_oOrganization, FolderType P_oFolderType, Document P_oDocument, AppDisplayMode displayMode = AppDisplayMode.Search)
            : this(P_oOrganization, P_oFolderType, displayMode)
        {
            CurrentDocument = P_oDocument;

        }

        /// <summary>
        /// Initializes a new instance of the <see cref="FolderPage" /> class.
        /// </summary>
        /// <param name="P_oOrganization">The organization.</param>
        /// <param name="P_oFolderType">Type of the folder.</param>
        /// <param name="p_oFolder">The folder.</param>
        /// <param name="displayMode">The display mode.</param>
        public FolderPage(Organization P_oOrganization, FolderType P_oFolderType, Folder p_oFolder, AppDisplayMode displayMode = AppDisplayMode.Search)
            : this(P_oOrganization, P_oFolderType, displayMode)
        {
            CurrentFolder = p_oFolder;

            WorkflowManager = new WorkflowManager()
            {
                Organization = CurrentOrganization,
                FolderType = CurrentFolderType,
                Folder = CurrentFolder
            };

            WorkflowManager.FilterChanged += WorkflowManagerFilterChanged;

            if (AppDisplayMode == AppDisplayMode.Search)
            {
                LoadDocumentsFolder();
            }

            AddHistoricConsultation();
        }

        #endregion

        public override void Dispose()
        {
            Loaded -= FolderPageLoaded;

            if (CommentChildWindow.IsOpen)
                CommentChildWindow.Close();

            if (_versioningManager != null)
            {
                _versioningManager.VersionCreated -= versioningManager_VersionCreated;
                _versioningManager.CreationError -= versioningManager_CreationError;
                _versioningManager.Dispose();
                _versioningManager = null;
            }

            if (WorkflowManager != null)
            {
                workflowToolbar.Dispose();

                WorkflowManager.FilterChanged -= WorkflowManagerFilterChanged;
                WorkflowManager.Processing -= WorkflowManagerProcessing;
                WorkflowManager.Processed -= WorkflowManagerProcessed;
                WorkflowManager.PropertyChanged -= WorkflowManagerPropertyChanged;
                WorkflowManager.Dispose();
                WorkflowManager = null;

                Messenger.Default.Unregister<NotificationMessageAction<IndexedFilesEventArgs>>(
                    this,
                    ActivateFlowIndexPanel);
            }

            if (m_oViewerControl != null)
            {
                m_oViewerControl.ActivateListMode -= ActivateListMode;
                m_oViewerControl.ActivateThumbnailMode -= ActivateThumbnailMode;
                m_oViewerControl.DisplayCompleted -= DisplayCompleted;
                m_oViewerControl.ItemsDeletedToRemove -= m_oListVignetteSearch_ItemsDeletedToRemove;
                m_oViewerControl.AddDocumentEvent -= OnAddDocumentEvent;
                m_oViewerControl.ItemsSelectedDocument -= m_oViewerControl_ItemsSelectedDocument;
                m_oViewerControl.ToolbarStateHasChanged -= m_oViewerControl_ToolbarStateHasChanged;
                m_oViewerControl.CreateNewVersionClick -= m_oViewerControl_CreateNewVersionClick;
                m_oViewerControl.MakeThisVersionToMajorClick -= m_oViewerControl_MakeThisVersionToMajorClick;
                m_oViewerControl.CopyPasteDocuments -= CopyPasteDocumentsHandle;
                m_oViewerControl.DocumentChanging -= m_oViewerControl_DocumentChanging;
                m_oViewerControl = null;
            }

            if (m_oListViewer != null)
            {
                m_oListViewer.ActivateThumbnailMode -= ActivateThumbnailMode;
                m_oListViewer.ActivateViewerMode -= ActivateViewerMode;
                m_oListViewer.ToolbarStateHasChanged -= m_oListViewer_ToolbarStateHasChanged;
                m_oListViewer.ItemsDeletedToRemove -= m_oListVignetteSearch_ItemsDeletedToRemove;
                m_oListViewer.ItemsSelectedToDisplay -= m_oListVignetteSearch_ItemsSelectedToDisplay;
                m_oListViewer.AddDocumentEvent -= OnAddDocumentEvent;
                m_oListViewer.CopyPasteDocuments -= CopyPasteDocumentsHandle;
                m_oListViewer.DisplayCompleted -= DisplayCompleted;
                m_oListViewer = null;
            }

            if (m_oListVignetteSearch != null)
            {
                m_oListVignetteSearch.ActivateViewerMode -= ActivateViewerMode;
                m_oListVignetteSearch.ActivateListMode -= ActivateListMode;
                m_oListVignetteSearch.ItemsSelectedToDisplay -= m_oListVignetteSearch_ItemsSelectedToDisplay;
                m_oListVignetteSearch.ItemsSelectedDocument -= m_oListVignetteSearch_ItemsSelectedDocument;
                m_oListVignetteSearch.ItemsLoaded -= m_oListVignetteSearch_ItemsLoaded;
                m_oListVignetteSearch.ItemsDeletedToRemove -= m_oListVignetteSearch_ItemsDeletedToRemove;
                m_oListVignetteSearch.AddDocumentEvent -= OnAddDocumentEvent;
                m_oListVignetteSearch.DocumentRankEventHandler -= m_oListVignetteSearch_DocumentRankEventHandler;
                m_oListVignetteSearch.CopyPasteDocuments -= CopyPasteDocumentsHandle;
                m_oListVignetteSearch.DisplayCompleted -= DisplayCompleted;
                m_oListVignetteSearch.Dispose();
                m_oListVignetteSearch = null;
            }

            ViewerControlPanel.Children.Clear();

            base.Dispose();
        }

        #region Init data


        /// <summary>
        /// Loads the folder document.
        /// </summary>
        /// <param name="p_oBehavior">The p_o behavior.</param>
        /// <param name="openCommentWindow">if set to <c>true</c> [open comment window].</param>
        public void LoadFolderDocument(Delegate p_oBehavior = null, bool openCommentWindow = false)
        {
            object[] l_oParams = new object[2];
            l_oParams[0] = p_oBehavior;
            l_oParams[1] = openCommentWindow;

            try
            {
                if (CurrentFolderType != null)
                {
                    BusinessEntitiesDomainContext businessEntitiesDomainContext = GlobalWebContext.BusinessEntitiesDomainContext;

                    if (CurrentDocument != null)
                    {
                        var query = businessEntitiesDomainContext.GetFolderQuery(
                            CurrentOrganization.Identifier,
                            CurrentFolderType.Identifier,
                            CurrentDocument.FolderId,
                            CurrentDocument.FolderIdentifier,
                            null);
                        businessEntitiesDomainContext.Load(query, OnGetFolderQueryCallback, l_oParams);
                    }
                    //Use for refresh after an update
                    else if (SelectedDocumentsFromThumbnails != null && SelectedDocumentsFromThumbnails.Count > 0)
                    {
                        if (SelectedDocumentsFromThumbnails[0] != null)
                        {
                            var query = businessEntitiesDomainContext.GetFolderQuery(
                                CurrentOrganization.Identifier,
                                CurrentFolderType.Identifier,
                                SelectedDocumentsFromThumbnails[0].FolderId,
                                SelectedDocumentsFromThumbnails[0].FolderIdentifier,
                                null);
                            businessEntitiesDomainContext.Load(query, OnGetFolderQueryCallback, l_oParams);
                        }
                    }
                    else
                    {
                        LoadDocumentsFolder(true);
                    }
                }
            }
            catch (Exception ex)
            {
                LoggerHelper.Send(this.GetType().Name, "LoadFolderDocument EXCEPTION : " + Environment.NewLine + ex.Message);
            }
        }

        /// <summary>
        /// Load document's folder
        /// </summary>
        /// <param name="result"></param>
        public void OnGetFolderQueryCallback(LoadOperation<Folder> result)
        {
            //load document's folder
            List<Folder> L_oListFolder = new List<Folder>(result.Entities);

            if (L_oListFolder.Count > 0)
            {
                CurrentFolder = L_oListFolder.First();

                object[] l_oParams = (object[])result.UserState;

                if (l_oParams[0] != null)
                {
                    Delegate d = (Delegate)l_oParams[0];
                    d.DynamicInvoke();
                }
                if (l_oParams[1] != null)
                {
                    if (Convert.ToBoolean(l_oParams[1]))
                    {
                        OpenCommentWindow(true);
                    }
                }
            }

            LoadDocumentsFolder();
        }

        /// <summary>
        /// enable to load folder's Documents
        /// </summary>
        public void LoadDocumentsFolder(bool reloadThumbnail = true)
        {
            try
            {
                CursorWait(this);

                if ((CurrentFolderType != null) && (CurrentFolder != null))
                {
                    BusinessEntitiesDomainContext businessEntitiesDomainContext = GlobalWebContext.BusinessEntitiesDomainContext;

                    if (AppDisplayMode == AppDisplayMode.Flow
                        && WorkflowManager != null
                        && WorkflowManager.WorkflowInstance != null
                        && WorkflowManager.SelectedFilter != null
                        && WorkflowManager.SelectedFilter.Value != WorkflowState.AllDocumentsInFolder)
                    {

                        if (WorkflowManager.IsSendMode)
                        {
                            var query = businessEntitiesDomainContext.GetWorkflowDocumentsByInstanceQuery(
                                CurrentFolderType.Identifier,
                                CurrentFolder.Identifier,
                                WorkflowManager.WorkflowInstance.RguId,
                                GlobalWebContext.CurrentUser.UserId,
                                WorkflowManager.WorkflowInstance.Identifier,
                                WorkflowManager.SelectedFilter.Value);
                            businessEntitiesDomainContext.Load(query, OnGetDocumentByFolderQueryCallback,
                                                               reloadThumbnail);
                        }
                        else
                        {
                            var query = businessEntitiesDomainContext.GetWorkflowDocumentsByUserQuery(
                                CurrentFolderType.Identifier,
                                CurrentFolder.Identifier,
                                WorkflowManager.WorkflowInstance.RguId,
                                GlobalWebContext.CurrentUser.UserId,
                                WorkflowManager.WorkflowInstance.InstanceUserId,
                                WorkflowManager.SelectedFilter.Value);
                            businessEntitiesDomainContext.Load(query, OnGetDocumentByFolderQueryCallback,
                                                               reloadThumbnail);
                        }
                    }
                    else
                    {
                        var query = businessEntitiesDomainContext.GetDocumentsQuery(
                            CurrentFolderType.Identifier,
                            CurrentFolder.Identifier);
                        businessEntitiesDomainContext.Load(query, OnGetDocumentByFolderQueryCallback, reloadThumbnail);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Write("EXCEPTION : " + Environment.NewLine + ex, Logger.Level.Error);
                CursorNormal(this);
            }
        }

        /// <summary>
        /// Get Document From SelectedItem
        /// </summary>
        /// <param name="P_olistNodeTreeView"> TreeVieeNode containing items</param>
        /// <returns>List of Document</returns>
        private List<Document> GetDocumentFromItem(DataItemTreeViewCollection P_olistNodeTreeView)
        {
            foreach (DataItemTreeView item in P_olistNodeTreeView)
            {
                if (m_oPreviousSelectedItem.IsTrashItem && item.IsTrashItem)
                {
                    return item.ListDocument;
                }
                else
                {
                    if (item.Code == CurrentDocument.ItemRank)
                    {
                        return item.ListDocument;
                    }
                    else
                    {
                        if ((item.Items != null) && (item.Items.Count > 0))
                        {
                            List<Document> L_oVerifDocumentFound = GetDocumentFromItem(item.Items);
                            if (L_oVerifDocumentFound != null)
                            {
                                return L_oVerifDocumentFound;
                            }
                        }
                    }
                }
            }

            return null;
        }

        /// <summary>
        /// Get CanConsult Item value From SelectedDocument
        /// </summary>
        /// <param name="listNodeTreeView"> TreeVieeNode containing items</param>
        /// <param name="P_oDocumentToSearch"> Selected Document</param>
        /// <returns>CanConsult Item value</returns>
        private bool? GetConsultFromDocument(DataItemTreeViewCollection listNodeTreeView, Document P_oDocumentToSearch)
        {
            foreach (DataItemTreeView item in listNodeTreeView)
            {
                if (m_oPreviousSelectedItem.IsTrashItem && item.IsTrashItem)
                {
                    return true;
                }
                if (item.Code == P_oDocumentToSearch.ItemRank)
                {
                    if (item.CanBeConsult)
                    {
                        return true;
                    }
                    return false;
                }
                if ((item.Items != null) && (item.Items.Count > 0))
                {
                    bool? l_oCanConsult = GetConsultFromDocument(item.Items, P_oDocumentToSearch);
                    if (l_oCanConsult == true)
                    {
                        return true;
                    }
                    if (l_oCanConsult == false)
                    {
                        return false;
                    }
                }
            }
            return null;
        }

        /// <summary>
        /// Load folder'sdocuments
        /// </summary>
        /// <param name="result"></param>
        private void OnGetDocumentByFolderQueryCallback(LoadOperation<Document> result)
        {
            bool l_bReloadThumbnail = (bool)result.UserState;

            //** Load folder's documents
            ListDocument = new ObservableCollection<Document>(result.Entities);

            //** Init item
            DataItemTreeViewCollection L_olistNodeTreeView = TreeViewControlItems.ItemsList;
            RefreshItemsDocuments(TreeViewControlItems.ItemsList);
            if (SelectedDocumentsFromThumbnails != null && SelectedDocumentsFromThumbnails.Count > 0)
            {
                if (SelectedItem != null && SelectedItem.CanBeConsult)
                {
                    if (l_bReloadThumbnail)
                        UpdateListDocumentFromSelectedItem();
                }
            }

            //** The current folder have documents
            if ((CurrentDocument == null) && (ListDocument.Count > 0))
            {
                foreach (Document L_oDocument in ListDocument)
                {
                    if (CurrentFolder != null && CurrentFolder.FullTextDocList != null)
                    {
                        if (CurrentFolder.FullTextDocList.Any(f => f.Equals(System.IO.Path.Combine(L_oDocument.RelativePath, L_oDocument.ImageName))))
                        {
                            if (GetConsultFromDocument(L_olistNodeTreeView, L_oDocument) == true)
                            {
                                CurrentDocument = L_oDocument;
                                break;
                            }
                        }
                    }
                    else
                    {
                        if (GetConsultFromDocument(L_olistNodeTreeView, L_oDocument) == true && m_bIsInit)
                        {
                            CurrentDocument = L_oDocument;
                            break;
                        }
                    }
                }
            }

            if (CurrentDocument != null) //** Load item's document
            {
                //Use to preserve the current selected document to reload
                Document currentDocumentBoforeLoad = CurrentDocument;
                if (L_olistNodeTreeView != null)
                {
                    m_oListSelectedDocumentFromItem = GetDocumentFromItem(L_olistNodeTreeView);
                }
                else
                {
                    m_oListSelectedDocumentFromItem = null;
                }

                // Init Thumbnails And Viewer Control. If already exist update ListDocument on ListVignetteSearch and Viewer controls.
                if (m_oViewerControl == null)
                {
                    InitListThumbnailsAndViewerControl(m_oListSelectedDocumentFromItem);
                }
                else
                {

                    //Load document in viewer 
                    CurrentDocument = currentDocumentBoforeLoad;

                    if (m_oViewerControl != null)
                    {
                        m_oViewerControl.ListDocument = m_oListSelectedDocumentFromItem;
                        m_oViewerControl.ListAllDocFileName = GetListFullNameItemDocument();
                        //LoadDocumentInViewer(CurrentDocument);
                    }
                    if (m_oListViewer != null)
                        m_oListViewer.ListDocument = m_oListSelectedDocumentFromItem;

                    if (m_oListVignetteSearch != null)
                        m_oListVignetteSearch.ListDocument = m_oListSelectedDocumentFromItem;

                    if (SelectedItem != null && SelectedItem.CanBeConsult)
                    {
                        if (l_bReloadThumbnail)
                            UpdateListDocumentFromSelectedItem();
                    }

                }
            }
            else //** No current document
            {
                if (m_bIsInit)
                {
                    TreeViewControlItems.SelectDefaultItem();
                }

                if (m_oViewerControl == null)
                {
                    InitListThumbnailsAndViewerControl(m_oListSelectedDocumentFromItem);
                }
                else
                {
                    m_oViewerControl.ListDocument = m_oListSelectedDocumentFromItem;
                    m_oViewerControl.ListAllDocFileName = GetListFullNameItemDocument();

                    if (m_oListViewer != null)
                        m_oListViewer.ListDocument = m_oListSelectedDocumentFromItem;

                    if (m_oListVignetteSearch != null)
                        m_oListVignetteSearch.ListDocument = m_oListSelectedDocumentFromItem;
                }
            }

            SplashScreenManager.Stop(this);
        }

        /// <summary>
        /// Init Thumbnails and viewer
        /// </summary>
        /// <param name="p_oListDocument"></param>
        private void InitListThumbnailsAndViewerControl(List<Document> p_oListDocument)
        {
            ViewerControlPanel.Children.Clear();
            m_oViewerControl = new UCViewer(p_oListDocument, AppDisplayMode, CurrentFolder, CurrentOrganization, CurrentFolderType)
            {
                Name = "ViewerControl",
                HorizontalAlignment = HorizontalAlignment.Stretch,
                VerticalAlignment = VerticalAlignment.Stretch
            };
            m_oViewerControl.SetValue(Grid.RowProperty, 0);
            m_oViewerControl.SetValue(Grid.ColumnProperty, 0);
            m_oViewerControl.InitialisationCompleted += m_oViewerControl_InitialisationCompleted;

            ViewerControlPanel.Children.Add(m_oViewerControl);
            DisplayMode = SelectModeDocument.Viewer;

            //init event handles
            m_oViewerControl.Visibility = Visibility.Visible;
            m_oViewerControl.ActivateListMode += ActivateListMode;
            m_oViewerControl.ActivateThumbnailMode += ActivateThumbnailMode;
            m_oViewerControl.DisplayCompleted += DisplayCompleted;
            m_oViewerControl.ItemsDeletedToRemove += m_oListVignetteSearch_ItemsDeletedToRemove;
            m_oViewerControl.AddDocumentEvent += OnAddDocumentEvent;
            m_oViewerControl.ItemsSelectedDocument += m_oViewerControl_ItemsSelectedDocument;
            m_oViewerControl.ItemsSelectedFileName += m_oViewerControl_ItemsSelectedDocument;
            m_oViewerControl.ToolbarStateHasChanged += m_oViewerControl_ToolbarStateHasChanged;
            m_oViewerControl.CreateNewVersionClick += m_oViewerControl_CreateNewVersionClick;
            m_oViewerControl.MakeThisVersionToMajorClick += m_oViewerControl_MakeThisVersionToMajorClick;
            m_oViewerControl.CopyPasteDocuments += CopyPasteDocumentsHandle;
            m_oViewerControl.DocumentChanging += m_oViewerControl_DocumentChanging;
            m_oViewerControl.ListDocumentUpdated += new EventHandler(m_oViewerControl_ListDocumentUpdated);
            m_oViewerControl.NewVersionAdded += versioningManager_VersionCreated;

            m_oViewerControl.DocumentToolbar.SetUserPriviledges(CurrentFolderType, CurrentOrganization);
            m_oViewerControl.DocumentContextMenu.SetUserPriviledges(CurrentFolderType, CurrentOrganization);
        }



        /// <summary>
        /// Select items which contain current Document
        /// </summary>
        /// <param name="P_olistNodeTreeView"> TreeViewNode representing items</param>
        /// <returns>Affected</returns>
        private bool SelectItemContainsDocument(DataItemTreeViewCollection P_olistNodeTreeView)
        {
            foreach (DataItemTreeView item in P_olistNodeTreeView)
            {
                if (item.Code == CurrentDocument.ItemRank)
                {
                    item.bIsSelected = true;
                    return true;
                }
                else
                {
                    if ((item.Items != null) && (item.Items.Count > 0))
                    {
                        if (SelectItemContainsDocument(item.Items))
                        {
                            return true;
                        }
                    }
                }
            }
            return false;
        }

        /// <summary>
        /// Display Document information
        /// It 's call when the variable 'Document' is affected to refresh document data
        /// </summary>
        private void InitDataDocument()
        {
            if (CurrentDocument != null)
            {
                DataItemTreeViewCollection L_olistNodeTreeView = TreeViewControlItems.ItemsList;
                if (SelectedItem != null && !SelectedItem.IsTrashItem)
                    SelectItemContainsDocument(L_olistNodeTreeView);
                ManageFolderInformations();

            }
            else
            {
                CurrentSelectedVersion = null;

                UpdateDocumentBarItemStyle(false);
            }
        }

        /// <summary>
        /// Find the document's imae to display it
        /// </summary>
        /// <param name="document"></param>
        private void LoadDocumentInViewer(Document document)
        {
            string L_szFileNameDoc;
            try
            {
                if (document != null)
                {
                    List<string> L_oListFullnameAllDocument = GetListFullNameItemDocument();
                    if ((L_oListFullnameAllDocument != null) && (L_oListFullnameAllDocument.Count > 0))
                    {
                        for (int i = 0; i < L_oListFullnameAllDocument.Count; i++)
                        {
                            L_szFileNameDoc = Path.GetFileNameWithoutExtension(L_oListFullnameAllDocument[i]);
                            if (L_szFileNameDoc != null)
                            {
                                if (L_szFileNameDoc.Equals(Path.GetFileNameWithoutExtension(document.ImageName)))
                                {
                                    //Be sure to be on the first page, loading another document
                                    //if (CurrentSelectedVersion == null)
                                    //    CurrentSelectedVersion = GetLastVersionItem(document);
                                    m_oViewerControl.ClearVersion();
                                    m_oViewerControl.ChangeConsultationMode(CurrentOrganization, CurrentFolderType, ConsultationModeType);
                                    m_oViewerControl.IndexPage = 1;

                                    if (document.AllVersion.Count == 0)
                                    {
                                        m_oViewerControl.LoadImageFromDocument(GlobalWebContext.CurrentUser.UserId, L_oListFullnameAllDocument, i, true);
                                    }
                                    else
                                    {
                                        var version = document.AllVersion.FirstOrDefault(); // first is the last version
                                        m_oViewerControl.LoadImageFromDocument(GlobalWebContext.CurrentUser.UserId, L_oListFullnameAllDocument, i, true, version.VersionId.ToString());
                                    }

                                    break;
                                }
                            }
                        }
                    }
                    else
                    {
                        m_oViewerControl.ClearViewer();
                    }
                }
                else
                {
                    m_oViewerControl.ReinitializeViewer();
                }
            }
            catch (Exception ex)
            {
                Logger.Write("EXCEPTION : " + Environment.NewLine + ex, Logger.Level.Error);
            }
        }

        #endregion

        #region Viewer events Handler

        /// <summary>
        /// Raised when a document is selected
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="DocumentSelectedEventArgs"/> instance containing the event data.</param>
        private void m_oViewerControl_ItemsSelectedDocument(object sender, DocumentSelectedEventArgs args)
        {
            m_oListVignetteSearch_ItemsSelectedDocument(sender, args);
        }

        /// <summary>
        /// Adds Thumbnail & listviewer control to the ViewerControlPanel
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void m_oViewerControl_InitialisationCompleted(object sender, EventArgs e)
        {
            /*
            * Initialization of m_oListVignetteSearch
            */
            if (CurrentDocument != null &&
                !string.IsNullOrEmpty(Path.GetExtension(CurrentDocument.ImageName)) &&
                !Path.GetExtension(CurrentDocument.ImageName).Equals(".zip", StringComparison.CurrentCultureIgnoreCase))
            {
                LoadDocumentInViewer(CurrentDocument);
            }

            m_oListVignetteSearch = new ListVignetteSearch(m_oListSelectedDocumentFromItem, CurrentFolder, m_bCanModify, CurrentOrganization, CurrentFolderType)
            {
                Name = "ListVignetteSearchControl",
                HorizontalAlignment = HorizontalAlignment.Stretch,
                VerticalAlignment = VerticalAlignment.Stretch,
                
            };

            m_oListVignetteSearch.CurrentDisplayMode = AppDisplayMode;

            m_oListVignetteSearch.SetValue(Grid.RowProperty, 0);
            m_oListVignetteSearch.SetValue(Grid.ColumnProperty, 0);
            m_oListVignetteSearch.SetValue(RadDragAndDropManager.AllowDragProperty, true);
            ViewerControlPanel.Children.Add(m_oListVignetteSearch);
            m_oListVignetteSearch.Desactivate();
            m_oListVignetteSearch.UserId = GlobalWebContext.CurrentUser.UserId;

            //Set user priviledges
            m_oListVignetteSearch.DocumentToolbar.SetUserPriviledges(CurrentFolderType, CurrentOrganization);
            m_oListVignetteSearch.DocumentContextMenu.SetUserPriviledges(CurrentFolderType, CurrentOrganization);

            //Init events handles
            m_oListVignetteSearch.ActivateViewerMode += ActivateViewerMode;
            m_oListVignetteSearch.ActivateListMode += ActivateListMode;
            m_oListVignetteSearch.ItemsSelectedToDisplay += m_oListVignetteSearch_ItemsSelectedToDisplay;
            m_oListVignetteSearch.ItemsSelectedDocument += m_oListVignetteSearch_ItemsSelectedDocument;
            m_oListVignetteSearch.ItemsSelectedFileName += m_oViewerControl_ItemsSelectedDocument;
            m_oListVignetteSearch.ItemsLoaded += m_oListVignetteSearch_ItemsLoaded;
            m_oListVignetteSearch.ItemsDeletedToRemove += m_oListVignetteSearch_ItemsDeletedToRemove;
            m_oListVignetteSearch.AddDocumentEvent += OnAddDocumentEvent;
            m_oListVignetteSearch.DocumentRankEventHandler += m_oListVignetteSearch_DocumentRankEventHandler;
            m_oListVignetteSearch.CopyPasteDocuments += CopyPasteDocumentsHandle;
            m_oListVignetteSearch.DisplayCompleted += DisplayCompleted;
            m_oListVignetteSearch.ActivateThumbnailMode += m_oListVignetteSearch_ActivateThumbnailMode;
            m_oViewerControl.NewVersionAdded += versioningManager_VersionCreated;

            /*
            * Initialization of ListViewer
            */

            m_oListViewer = new ListViewer(AppDisplayMode.Search, CurrentFolder, CurrentOrganization, CurrentFolderType)
            {
                Name = "ListViewer",
                Visibility = System.Windows.Visibility.Collapsed,
            };

            m_oListViewer.CurrentDisplayMode = AppDisplayMode;

            m_oListViewer.SetValue(Grid.RowProperty, 0);
            m_oListViewer.SetValue(Grid.ColumnProperty, 0);
            ViewerControlPanel.Children.Add(m_oListViewer);
            m_oListViewer.UserId = GlobalWebContext.CurrentUser.UserId;
            m_oListViewer.ActivateThumbnailMode += ActivateThumbnailMode;
            m_oListViewer.ActivateViewerMode += ActivateViewerMode;
            m_oListViewer.ItemsDeletedToRemove += m_oListVignetteSearch_ItemsDeletedToRemove;
            m_oListViewer.ItemsSelectedToDisplay += m_oListVignetteSearch_ItemsSelectedToDisplay;
            m_oListViewer.ItemsSelectedDocument += m_oListVignetteSearch_ItemsSelectedDocument;
            m_oListViewer.ItemsSelectedFileName += m_oViewerControl_ItemsSelectedDocument;
            m_oListViewer.AddDocumentEvent += OnAddDocumentEvent;
            m_oListViewer.CopyPasteDocuments += CopyPasteDocumentsHandle;
            m_oListViewer.DisplayCompleted += DisplayCompleted;
            m_oListViewer.ToolbarStateHasChanged += m_oListViewer_ToolbarStateHasChanged;
            m_oListViewer.NewVersionAdded += versioningManager_VersionCreated;
            m_oListViewer.ActivateListMode += ActivateListMode;

            //Set user priviledges
            m_oListViewer.DocumentToolbar.SetUserPriviledges(CurrentFolderType, CurrentOrganization);
            m_oListViewer.DocumentContextMenu.SetUserPriviledges(CurrentFolderType, CurrentOrganization);

            /*
             * Add Drag'n Drop between ListVignetteSearch/ListViewer and Items Tree View
             */

            RadDragAndDropManager.AddDragQueryHandler(m_oListVignetteSearch, OnDocumentsToItemDragQuery);
            RadDragAndDropManager.AddDragInfoHandler(m_oListVignetteSearch, OnDocumentsToItemDragInfo);
            RadDragAndDropManager.AddDropInfoHandler(m_oListVignetteSearch, OnDocumentsToItemDropInfo);
            RadDragAndDropManager.AddDropQueryHandler(m_oListVignetteSearch, OnDocumentsToItemDropQuery);

            RadDragAndDropManager.AddDragQueryHandler(m_oListViewer.GridViewDoc, OnDocumentsToItemDragQuery);
            RadDragAndDropManager.AddDragInfoHandler(m_oListViewer.GridViewDoc, OnDocumentsToItemDragInfo);
            RadDragAndDropManager.AddDropInfoHandler(m_oListViewer.GridViewDoc, OnDocumentsToItemDropInfo);
            RadDragAndDropManager.AddDropQueryHandler(m_oListViewer.GridViewDoc, OnDocumentsToItemDropQuery);

            RadDragAndDropManager.AddDragQueryHandler(TreeViewControlItems.TreeViewControlItems, OnDocumentsToItemDragQuery);
            RadDragAndDropManager.AddDragInfoHandler(TreeViewControlItems.TreeViewControlItems, OnDocumentsToItemDragInfo);
            RadDragAndDropManager.AddDropInfoHandler(TreeViewControlItems.TreeViewControlItems, OnDocumentsToItemDropInfo);
            RadDragAndDropManager.AddDropQueryHandler(TreeViewControlItems.TreeViewControlItems, OnDocumentsToItemDropQuery);

            if (CurrentDocument != null && 
                !string.IsNullOrEmpty(Path.GetExtension(CurrentDocument.ImageName)) 
                && Path.GetExtension(CurrentDocument.ImageName).Equals(".zip", StringComparison.CurrentCultureIgnoreCase))
            {
                List<Document> documents = GetDocumentFromItem(TreeViewControlItems.ItemsList);

                ActivateThumbnailMode(this, null);

                UpdateListDocumentFromSelectedItem(documents);
            }
            
        }

        /// <summary>
        /// The toolbar in the viewer control has changed, we must to reload permissions
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void m_oViewerControl_ToolbarStateHasChanged(object sender, EventArgs e)
        {
            //if (SelectedItem.IsTrashItem)
            //{
            //    ManageConsultationMode(ConsultationModeType.Trash);
            //}
            //else
            //{
            //    ManageConsultationMode(ConsultationModeType.Disable);
            //}
        }

        /// <summary>
        /// Raised when navigation bar is clicked.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void m_oViewerControl_DocumentChanging(object sender, EventArgs e)
        {
            CurrentSelectedVersion = null;
            ManageFolderInformations();
        }

        /// <summary>
        /// Handles the ListDocumentUpdated event of the m_oViewerControl control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs" /> instance containing the event data.</param>
        private void m_oViewerControl_ListDocumentUpdated(object sender, EventArgs e)
        {
        }

        #endregion

        #region Thumbnail events Handler

        /// <summary>
        /// Handles ToolbarStateHasChanged event of thumbnail control
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void m_oListVignetteSearch_ToolbarStateHasChanged(object sender, EventArgs e)
        {
            //if (SelectedItem.IsTrashItem)
            //{
            //    ManageConsultationMode(ConsultationModeType.Trash);
            //}
            //else
            //{
            //    ManageConsultationMode(ConsultationModeType.Disable);
            //}
        }

        /// <summary>
        /// Handles DocumentRankEventHandler event of thumbnail control
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void m_oListVignetteSearch_DocumentRankEventHandler(object sender, EventArgs e)
        {
            //Set to false to avoid the case of when a drag'n drop is performed and we change the folder after the refresh the previous selection is retrieved
            //Use in callbacks of LoadDocumentsFolder
            m_bIsInit = false;

            //InitItems(false);

            LoadDocumentsFolder(false);
        }

        /// <summary>
        /// Raise when items are deleted in the ListVignette
        /// </summary>
        /// <param name="p_oListDocumentToRemove">List of document to remove.</param>
        private void m_oListVignetteSearch_ItemsDeletedToRemove(List<Document> p_oListDocumentToRemove)
        {
            foreach (Document DocumentDeleted in p_oListDocumentToRemove)
            {
                ListDocument.Remove(DocumentDeleted);
                OnDataHasChanged();
            }

            RefreshItemsDocuments(TreeViewControlItems.ItemsList);
        }

        /// <summary>
        /// Raise when items are selected in the ListVignette
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="args">The <see cref="Rio.Framework.Pages.Events.DocumentSelectedEventArgs"/> instance containing the event data.</param>
        private void m_oListVignetteSearch_ItemsSelectedDocument(object sender, DocumentSelectedEventArgs args)
        {
            if ((args.p_oListDocument != null) && (args.p_oListDocument.Count > 0))
            {
                if (args.p_oListDocument.Count == 1)
                {
                    if (DisplayMode == SelectModeDocument.Viewer)
                    {
                        //We select the document to display its data
                        CurrentDocument = args.p_oListDocument[0];

                    }
                    else
                    {
                        CurrentDocument = args.p_oListDocument[0];
                        SelectedDocumentsFromThumbnails = new ObservableCollection<Document> { args.p_oListDocument[0] };
                    }
                }
                else
                {
                    if (DisplayMode == SelectModeDocument.Viewer)
                    {
                        // we have selected more of one document so we can't display data document
                        CurrentDocument = null;
                        CurrentSelectedVersion = null;
                    }
                    else
                    {
                        //we save all the selected document to update them with the same data document
                        CurrentDocument = null;
                        CurrentSelectedVersion = null;
                        SelectedDocumentsFromThumbnails = new ObservableCollection<Document>(args.p_oListDocument);
                    }
                }

                //Update the list of document inside the flow index panel 
                UpdateFlowIndexPanelWithSelectedDocument();

            }
            else if (args.ListAllFileName != null)
            {
                if (args.ListAllFileName.Count == 1)
                {
                    if (DisplayMode == SelectModeDocument.Viewer)
                    {
                        CurrentDocument = ListDocument.SingleOrDefault(d => Path.Combine(d.RelativePath, d.ImageName).ToLowerInvariant() ==
                                                                            args.ListAllFileName[0].ToLowerInvariant());
                    }
                    else
                    {
                        SelectedDocumentsFromThumbnails = new ObservableCollection<Document>(
                            ListDocument.Where(d =>
                                Path.Combine(d.RelativePath, d.ImageName).ToLowerInvariant() == args.ListAllFileName[0].ToLowerInvariant()));
                    }
                }
                else
                {
                    if (DisplayMode == SelectModeDocument.Viewer)
                    {
                        CurrentDocument = null;
                        CurrentSelectedVersion = null;
                    }
                    else
                    {
                        SelectedDocumentsFromThumbnails = new ObservableCollection<Document>(from filename in args.ListAllFileName
                                                                                             from document in ListDocument
                                                                                             where filename.ToLowerInvariant() == Path.Combine(document.RelativePath, document.ImageName).ToLowerInvariant()
                                                                                             select document);
                    }
                }

                //Update the list of document inside the flow index panel 
                UpdateFlowIndexPanelWithSelectedDocument();

            }
            else
            {
                //Nothing document are selected, so we remove displayed document data by puting null value 
                CurrentDocument = null;
                CurrentSelectedVersion = null;

                SelectedDocumentsFromThumbnails = null;
            }

            
        }

        /// <summary>
        /// Raise when an item is selected in the ListVignette by a double click
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="DocumentSelectedEventArgs"/> instance containing the event data.</param>
        private void m_oListVignetteSearch_ItemsSelectedToDisplay(object sender, DocumentSelectedEventArgs args)
        {
            List<string> l_oListDocument;
            if ((args.p_oListDocument != null) && (args.p_oListDocument.Count > 0))
            {
                l_oListDocument = m_oListVignetteSearch.GetListFullNameAllDocument();
                DisplayMode = SelectModeDocument.Viewer;
                m_oViewerControl.ClearVersion();
                m_oViewerControl.IndexPage = 1;
                m_oViewerControl.ListDocument = m_oListVignetteSearch.GetListAllDocuments();
                m_oViewerControl.LoadImageFromDocument(GlobalWebContext.CurrentUser.UserId, l_oListDocument, args.SelectedDocumentIndex, true);
                m_oViewerControl.Visibility = Visibility.Visible;
                m_oListViewer.Visibility = System.Windows.Visibility.Collapsed;
                m_oListVignetteSearch.Desactivate();
            }
        }

        /// <summary>
        /// Raise ItemsLoaded event of the Thumbnail control
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void m_oListVignetteSearch_ItemsLoaded(object sender, DocumentSelectedEventArgs e)
        {
            if (DisplayMode == SelectModeDocument.Viewer)
            {
                LoadDocumentInViewer(CurrentDocument);
            }
            else
            {
                m_oListVignetteSearch.Activate(m_oViewerControl.SelectedDocumentIndex);
                m_oListViewer.SelectedImageIndex = m_oViewerControl.SelectedDocumentIndex;
            }

            m_oListViewer.Images = e.ListAllRioImagesSearch;
        }

        /// <summary>
        /// Handles the ActivateThumbnailMode event of the m_oListVignetteSearch control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs" /> instance containing the event data.</param>
        private void m_oListVignetteSearch_ActivateThumbnailMode(object sender, EventArgs e)
        {
        }

        #endregion

        #region ListViewer events Handler

        /// <summary>
        /// Handles ToolbarStateHasChanged event of listviewer control
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void m_oListViewer_ToolbarStateHasChanged(object sender, EventArgs e)
        {
            //if (SelectedItem.IsTrashItem)
            //{
            //    ManageConsultationMode(ConsultationModeType.Trash);
            //}
            //else
            //{
            //    ManageConsultationMode(ConsultationModeType.Disable);
            //}
        }


        #endregion

        #region Common viewer events handler

        /// <summary>
        /// Raised when we go to List mode.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void ActivateListMode(object sender, EventArgs e)
        {
            CurrentSelectedVersion = null;

            UpdateListDocumentFromSelectedItem();

            //Hide single and thumbnail viewer
            m_oViewerControl.Visibility = Visibility.Collapsed;
            m_oListVignetteSearch.Visibility = Visibility.Collapsed;
            m_oListViewer.Visibility = Visibility.Visible;

            //Init list viewer
            m_oListViewer.UserId = m_oListVignetteSearch.UserId;
            m_oListViewer.UserId = m_oListVignetteSearch.UserId;
            m_oListViewer.Images = m_oListVignetteSearch.ListItemSource;
            m_oListViewer.Visibility = Visibility.Visible;
            m_oListViewer.ListAllDocFileName = m_oListVignetteSearch.ListAllDocFileName;
            m_oListViewer.m_oItemsSource = m_oListVignetteSearch.m_oItemsSource;

            //Set selected images
            UCViewerCore viewer = GetCurrentViewer();
            List<ImageRioSearch> images = viewer.GetSelectedImage<ImageRioSearch>();
            if (images != null && images.Count > 0)
            {
                m_oListViewer.SetSelectedImage<ImageRioSearch>(images);
            }

            DisplayMode = SelectModeDocument.List;
            UpdateListDocumentFromSelectedItem();
            m_oListViewer.ManageToolbarState();
            m_oListVignetteSearch.Desactivate();
            m_oViewerControl.ClearViewer();
            ReloadPasteMenuVisibility();
        }

        /// <summary>
        /// Raised when we go to Thumbnail mode.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void ActivateThumbnailMode(object sender, EventArgs e)
        {
            m_oListViewer.Visibility = Visibility.Collapsed;
            m_oViewerControl.Visibility = Visibility.Collapsed;
            m_oListVignetteSearch.Visibility = Visibility.Visible;

            //Set selected images
            UCViewerCore viewer = GetCurrentViewer();
            List<ImageRioSearch> images = viewer.GetSelectedImage<ImageRioSearch>();
            if (images != null && images.Count > 0)
            {
                m_oListVignetteSearch.SetSelectedImage<ImageRioSearch>(images);
            }

            DisplayMode = SelectModeDocument.Thumbnail;
            
            UpdateListDocumentFromSelectedItem();
            
            m_oListVignetteSearch.SelectedDocumentIndex = 0;
            m_oListVignetteSearch.m_oListDocument = m_oListSelectedDocumentFromItem;
            m_oListVignetteSearch.ManageToolbarState();

            m_oViewerControl.ClearViewer();
            ReloadPasteMenuVisibility();

        }

        /// <summary>
        /// Raised when we go to Viewer mode.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void ActivateViewerMode(object sender, EventArgs e)
        {
            CurrentSelectedVersion = null;
            DisplayMode = SelectModeDocument.Viewer;

            m_oListVignetteSearch.Desactivate();
            m_oViewerControl.Visibility = Visibility.Visible;
            m_oListViewer.Visibility = Visibility.Collapsed;

            UpdateListDocumentFromSelectedItem();
            ReloadPasteMenuVisibility();
        }

        /// <summary>
        /// Raised when a document is double clicked
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void DisplayCompleted(object sender, EventArgs e)
        {
            Framework.Pages.ModalControls.ModalDialogController.Close();
            CursorNormal(this);
            m_oSplashScreen.Close();
            if (ConsultationModeType != AppCode.Enums.ConsultationModeType.Disable)
                EnableDisableConsultationMode(ConsultationModeType);

        }

        #endregion

        #region Index

        /// <summary>
        /// Buttons the cancel update index click.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs" /> instance containing the event data.</param>
        private void ButtonCancelUpdateIndexClick(object sender, RoutedEventArgs e)
        {
            SwitchIndexButtonVisibility(false);
            StackIndex.Rebind();
        }

        /// <summary>
        /// Gets the display index value.
        /// </summary>
        /// <param name="rawValue">The raw value.</param>
        /// <returns></returns>
        private string GetDisplayIndexValue(string rawValue)
        {
            string[] L_oTabValue = rawValue.Split(new[] { ';' });

            return L_oTabValue[0];
        }

        #endregion

        #region Items

        /// <summary>
        /// Initialize items'treeview from a XDocument
        /// </summary>
        private void InitItems(bool isInit = true)
        {
            TreeViewControlItems.InitItems(CurrentFolderType);
            if (CurrentFolder != null)
            {
                AddOrRefreshTrashItemInTreeView();
            }

            if (isInit)
            {
                TreeViewControlItems.SelectDefaultItem();
                m_oPreviousSelectedItem = SelectedItem;
            }
        }

        /// <summary>
        /// Adds the trash item in tree view.
        /// </summary>
        private void AddOrRefreshTrashItemInTreeView()
        {
            BusinessEntitiesDomainContext businessEntitiesDomainContext = GlobalWebContext.BusinessEntitiesDomainContext;
            var getDeletedDocumentsQuery = businessEntitiesDomainContext.GetDeletedDocumentsQuery(CurrentFolderType.Identifier, CurrentFolder.Identifier);

            businessEntitiesDomainContext.Load<Document>(
                getDeletedDocumentsQuery,
                delegate(LoadOperation<Document> result)
                {
                    if (TreeViewControlItems.ContainTrashItem)
                    {
                        DataItemTreeView dataItemTreeView = TreeViewControlItems.GetTrashItem();
                        if (dataItemTreeView != null)
                            dataItemTreeView.ListDocument = new List<Document>(result.Entities);
                    }
                    else
                    {
                        TreeViewControlItems.AddTrashItem(new List<Document>(result.Entities));
                    }
                },
                null);
        }

        /// <summary>
        /// Enable to indicate the number of document in an Item
        /// </summary>
        /// <param name="dataItemTreeViewCollection">The data item tree view collection.</param>
        private void RefreshItemsDocuments(DataItemTreeViewCollection dataItemTreeViewCollection)
        {
            if ((dataItemTreeViewCollection != null) && (dataItemTreeViewCollection.Count > 0))
            {
                foreach (DataItemTreeView item in dataItemTreeViewCollection)
                {
                    if (!item.IsTrashItem)
                    {
                        item.ListDocument = ListDocument.Where(p => p.ItemRank == item.Code).ToList();
                        if (item.ItemsCount > 0)
                        {
                            ExpandItem(item);
                        }

                        RefreshItemsDocuments(item.Items);
                    }
                    else
                    {
                        AddOrRefreshTrashItemInTreeView();
                    }
                }
            }
        }

        /// <summary>
        /// Expand parent's item
        /// </summary>
        /// <param name="P_oDataItemTreeView"></param>
        private void ExpandItem(DataItemTreeView P_oDataItemTreeView)
        {
            if (P_oDataItemTreeView.Parent != null)
            {
                P_oDataItemTreeView.Parent.bIsExpanded = true;
                ExpandItem(P_oDataItemTreeView.Parent);
            }
        }

        /// <summary>
        /// Update document list from selected item
        /// </summary>
        /// <param name="documents"></param>
        private void UpdateListDocumentFromSelectedItem(List<Document> documents = null)
        {
            bool l_bItemHasChanged = false;
            if (m_oCurrentSelectedItem == null || m_oCurrentSelectedItem.Code != SelectedItem.Code)
                l_bItemHasChanged = true;
            m_oCurrentSelectedItem = SelectedItem;

            #region Retreive selected items from TreeView 'm_oListSelectedDocumentFromItem' updated

            if (documents == null)
            {
                if (TreeViewControlItems != null && SelectedItem != null)
                {
                    m_oListSelectedDocumentFromItem = SelectedItem.ListDocument;
                }
                else
                {
                    m_oListSelectedDocumentFromItem = null;
                }
            }
            else
            {
                DataItemTreeView trashItem = TreeViewControlItems.ItemsList.Where(item => (item).IsTrashItem).FirstOrDefault();
                if (trashItem != null)
                {
                    trashItem.ListDocument = documents;
                    m_oListSelectedDocumentFromItem = documents;
                }
            }

            #endregion

            #region Update CurrentDocument
            if (m_oListSelectedDocumentFromItem != null && m_oListSelectedDocumentFromItem.Count > 0)
            {
                if (CurrentDocument == null || !(m_oListSelectedDocumentFromItem.Any(doc => doc.Identifier == CurrentDocument.Identifier)))
                {
                    CurrentDocument = m_oListSelectedDocumentFromItem.FirstOrDefault();
                }
                else
                {
                    CurrentDocument =
                        m_oListSelectedDocumentFromItem.Where(doc => doc.Identifier == CurrentDocument.Identifier).
                            FirstOrDefault();
                }

                //if (((CurrentDocument == null) || (m_oListSelectedDocumentFromItem.Contains(CurrentDocument) == false)))
                //{
                //    CurrentDocument = m_oListSelectedDocumentFromItem[0];
                //}
            }
            else
            {
                CurrentDocument = null;
            }
            #endregion

            #region refresh the activate display mode
            if (DisplayMode == SelectModeDocument.Viewer)
            {
                if (m_oListSelectedDocumentFromItem != null)
                {
                    m_oViewerControl.ListDocument = m_oListSelectedDocumentFromItem;
                }
                LoadDocumentInViewer(CurrentDocument);
            }

            //Not necessary to reload thumbnails if the number of documents are identical:
            //      Reason: No way to alter the document(rotate...etc). Add, delete, change item will change the number of documents anyway
            if (m_oListVignetteSearch != null && m_oListVignetteSearch.ListDocument != null)
            {
                if (m_oListSelectedDocumentFromItem != null && ((m_oListVignetteSearch.ListBoxItems.Count == 0 && m_oListVignetteSearch.ListDocument.Count > 0) ||
                                                                (m_oListVignetteSearch.ListDocument.Count != m_oListSelectedDocumentFromItem.Count) ||
                                                                l_bItemHasChanged))
                {
                    if (DisplayMode != SelectModeDocument.Viewer)
                    {
                        m_oListVignetteSearch.ListDocument = m_oListSelectedDocumentFromItem;
                        m_oListViewer.ListDocument = m_oListSelectedDocumentFromItem;
                    }
                }
            }
            else
            {
                if (DisplayMode != SelectModeDocument.Viewer)
                {
                    if (m_oListVignetteSearch != null)
                    {
                        m_oListVignetteSearch.ListDocument = m_oListSelectedDocumentFromItem;
                    }
                    m_oListViewer.ListDocument = m_oListSelectedDocumentFromItem;
                }
            }
            #endregion
        }

        /// <summary>
        /// Handles the ItemChanged event of the TreeViewControlItems control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="args">The <see cref="Rio.Framework.Pages.AppCode.Events.TreeItemEventArgs" /> instance containing the event data.</param>
        private void TreeViewControlItems_ItemChanged(object sender, TreeItemEventArgs args)
        {
            if (args.CurrentSelectedItem != null)
            {
                DataItemTreeView L_oDITVSelected = args.CurrentSelectedItem;
                if (!args.CurrentSelectedItem.IsDefaultItem)
                {
                    buttonUpdateDocumentItem.IsEnabled = L_oDITVSelected.CanBeModify;
                }
            }
            if (TreeViewControlItems.ItemsList.Count == 1)
            {
                buttonUpdateDocumentItem.IsEnabled = false;
            }

            buttonUpdateDocumentItem.IsEnabled = !SelectedItem.IsTrashItem;
        }

        /// <summary>
        /// Handles the ItemDblClicked event of the TreeViewControlItems control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="args">The <see cref="Rio.Framework.Pages.AppCode.Events.TreeItemEventArgs" /> instance containing the event data.</param>
        private void TreeViewControlItems_ItemDblClicked(object sender, TreeItemEventArgs args)
        {
            //Save previous item 
            if (TreeViewControlItems != null && SelectedItem != null)
            {
                m_oPreviousSelectedItem = SelectedItem;
            }

            if (SelectedItem != null)
            {
                buttonUpdateDocumentItem.Visibility = SelectedItem.IsTrashItem ? Visibility.Collapsed : System.Windows.Visibility.Visible;
                buttonRestoreDocuments.Visibility = SelectedItem.IsTrashItem ? Visibility.Visible : System.Windows.Visibility.Collapsed;

                //If user can consult the item
                if (SelectedItem.CanBeConsult)
                {
                    CurrentSelectedVersion = null;

                    if (!SelectedItem.IsTrashItem)
                    {
                        ManageConsultationMode(ConsultationModeType.Disable);
                        UpdateListDocumentFromSelectedItem();
                        DocumentInfo.IsEnabled = m_bCanModify;
                    }
                    else
                    {
                        ManageConsultationMode(ConsultationModeType.Trash);
                        LoadTrashDocuments();
                        DocumentInfo.IsEnabled = false;
                    }

                    //Manage menus accessibility
                    if (m_oViewerControl.ListAllDocFileName == null || m_oViewerControl.ListAllDocFileName.Count == 0 ||
                        CurrentFolder.FullTextDocList == null || !CurrentFolder.FullTextDocList.Contains(m_oViewerControl.ListAllDocFileName[m_oViewerControl.SelectedDocumentIndex]))
                    {
                        m_oViewerControl.DocumentToolbar.SetAvailability(DocumentRibbonBarMenuItems.SearchPrevious, false);
                        m_oViewerControl.DocumentToolbar.SetAvailability(DocumentRibbonBarMenuItems.SearchNext, false);
                    }
                    else
                    {
                        m_oViewerControl.DocumentToolbar.SetAvailability(DocumentRibbonBarMenuItems.SearchPrevious, true);
                        m_oViewerControl.DocumentToolbar.SetAvailability(DocumentRibbonBarMenuItems.SearchNext, true);
                    }

                    if (m_oViewerControl.ListAllDocFileName == null ||
                        m_oViewerControl.ListAllDocFileName.Count == 0)
                    {
                        m_oViewerControl.DocumentToolbar.SetAvailability(DocumentRibbonBarMenuItems.FitHeight, false);
                        m_oViewerControl.DocumentToolbar.SetAvailability(DocumentRibbonBarMenuItems.FitWidth, false);
                    }
                    else
                    {
                        m_oViewerControl.DocumentToolbar.SetAvailability(DocumentRibbonBarMenuItems.FitHeight, true);
                        m_oViewerControl.DocumentToolbar.SetAvailability(DocumentRibbonBarMenuItems.FitWidth, true);
                    }
                }
                else
                {
                    MessageBoxChildWindow L_oMessage = new MessageBoxChildWindow(String.Empty, m_sLabelCantConsult, MessageBoxButtons.Ok, MessageBoxIcon.Warning);
                    L_oMessage.ShowDialog();
                }
            }
        }

        #endregion

        #region Update Folder & document

        /// <summary>
        /// Switches the index button visibility.
        /// </summary>
        /// <param name="active">The active.</param>
        private void SwitchIndexButtonVisibility(bool active)
        {
            if (active)
            {
                indexContentControl.IsEnabled = true;
                buttonUpdateIndex.Content = m_sLabelButtonSaveIndex;
                buttonCancelUpdateIndex.Visibility = System.Windows.Visibility.Visible;
            }
            else
            {
                indexContentControl.IsEnabled = false;
                buttonUpdateIndex.Content = m_sLabelButtonModifyIndex;
                buttonCancelUpdateIndex.Visibility = System.Windows.Visibility.Collapsed;
            }
        }

        /// <summary>
        /// Update index folder
        /// </summary>
        private void UpdateFolder()
        {
            DesactivatePanel();

            //List of criteria and values
            Dictionary<string, string> l_oCriteriaFilter;
            Dictionary<long, string> l_oUnicityIndex;

            //If all mandatory criteria are inputed, we can follow the indexation
            if (StackIndex.IsMandatoryIndexSatisfied())
            {
                BusinessEntitiesDomainContext businessEntitiesDomainContext = GlobalWebContext.BusinessEntitiesDomainContext;

                Dictionary<long, string> l_oCriteriaIndex = StackIndex.GetIndexIdValues();
                l_oUnicityIndex = StackIndex.GetUniqueIndexValues();
                l_oCriteriaFilter = StackIndex.GetIndexNameValues();

                // Check if a folder exist with index 
                businessEntitiesDomainContext.IsFolderExist(CurrentOrganization.Identifier, CurrentFolderType.Identifier, l_oCriteriaIndex, true, delegate(InvokeOperation<ReturnLong> retr)
                {
                    if (retr != null && retr.Value != null && retr.Value.Value != 0)
                    {
                        if (retr.Value.Value == CurrentFolder.Identifier)
                        {
                            //** check unicity of index
                            businessEntitiesDomainContext.CheckUnicityOfIndexValue(CurrentFolderType.Identifier, l_oUnicityIndex, CurrentFolder.Identifier, delegate(InvokeOperation<IEnumerable<long>> CheckUnicityReturn)
                            {
                                if (CheckUnicityReturn.Value != null && CheckUnicityReturn.Value.Count() == 0)
                                {
                                    var query = businessEntitiesDomainContext.UpdateFolderIndexQuery(CurrentFolderType.Identifier, CurrentFolder.Identifier, l_oCriteriaFilter);
                                    businessEntitiesDomainContext.Load(query, OnUpdateFolderCallback, null);
                                }
                                else
                                {
                                    //highlight control
                                    List<long> l_oListIndex = new List<long>(CheckUnicityReturn.Value);
                                    StackIndex.ChangeBorderColor(l_oListIndex, Colors.Red);
                                    ;
                                    ActivatePanel();
                                    MessageBoxChildWindow L_oMessage = new MessageBoxChildWindow("", m_szMsgNoUnicity, MessageBoxButtons.Ok, MessageBoxIcon.Warning);
                                    L_oMessage.ShowDialog();
                                }
                            }, null);
                        }
                        else
                        {
                            ActivatePanel();
                            MessageBoxChildWindow L_oMessage = new MessageBoxChildWindow("", m_szMsgFolderExist, MessageBoxButtons.Ok, MessageBoxIcon.Warning);
                            L_oMessage.ShowDialog();
                        }
                    }
                    else
                    {
                        //** check unicity of index
                        businessEntitiesDomainContext.CheckUnicityOfIndexValue(CurrentFolderType.Identifier, l_oUnicityIndex, CurrentFolder.Identifier, delegate(InvokeOperation<IEnumerable<long>> CheckUnicityReturn)
                        {
                            if (CheckUnicityReturn.Value != null && CheckUnicityReturn.Value.Count() == 0)
                            {
                                var query = businessEntitiesDomainContext.UpdateFolderIndexQuery(CurrentFolderType.Identifier, CurrentFolder.Identifier, l_oCriteriaFilter);
                                businessEntitiesDomainContext.Load(query, OnUpdateFolderCallback, null);
                            }
                            else
                            {
                                //highlight control
                                List<long> l_oListIndex = new List<long>(CheckUnicityReturn.Value);
                                StackIndex.ChangeBorderColor(l_oListIndex, Colors.Red);
                                ActivatePanel();
                                MessageBoxChildWindow L_oMessage = new MessageBoxChildWindow("", m_szMsgNoUnicity, MessageBoxButtons.Ok, MessageBoxIcon.Warning);
                                L_oMessage.ShowDialog();
                            }
                        }, null);
                    }
                }, null);//IsFolderExist
            }
            else
            {
                ActivatePanel();
                MessageBoxChildWindow L_oMessage = new MessageBoxChildWindow("", m_szMessageMandatoryField, MessageBoxButtons.Ok, MessageBoxIcon.Warning);
                L_oMessage.ShowDialog();
            }
        }

        /// <summary>
        /// Called when [update folder callback].
        /// </summary>
        /// <param name="result">The result.</param>
        private void OnUpdateFolderCallback(LoadOperation result)
        {
            indexScrollViewer.ScrollToTop();

            MessageBoxChildWindow L_oMessage;
            if (result.HasError)
            {
                Logger.Write("EXCEPTION : " + Environment.NewLine + result.Error.Message, Logger.Level.Error);
                L_oMessage = new MessageBoxChildWindow("", m_szUpdateFailed, MessageBoxButtons.Ok, MessageBoxIcon.Warning);
                L_oMessage.Show();
                L_oMessage.Closed += (s, ev) => ActivatePanel();
            }
            else
            {
                SwitchIndexButtonVisibility(false);

                //Update the current folder with the index up to date
                GetFolder();
            }
        }

        /// <summary>
        /// Gets the folder.
        /// </summary>
        private void GetFolder()
        {
            BusinessEntitiesDomainContext businessEntitiesDomainContext = GlobalWebContext.BusinessEntitiesDomainContext;
            var query = businessEntitiesDomainContext.GetFolderQuery(CurrentOrganization.Identifier, CurrentFolderType.Identifier, CurrentFolder.Identifier, CurrentFolder.Iddoc, null);
            businessEntitiesDomainContext.Load(query, OnOnGetFolderQueryCallback, null);
        }

        /// <summary>
        /// Callback og the GetFolder query
        /// </summary>
        /// <param name="result"></param>
        private void OnOnGetFolderQueryCallback(LoadOperation<Folder> result)
        {
            List<Folder> l_oFolderList = new List<Folder>(result.Entities);
            CurrentFolder = l_oFolderList.First();
            OnDataHasChanged();
            MessageBoxChildWindow L_oMessage = new MessageBoxChildWindow("", m_szUpdateValidation, MessageBoxButtons.Ok, MessageBoxIcon.Information);
            L_oMessage.ShowDialog();
            L_oMessage.Closed += (s, ev) => ActivatePanel();
        }

        /// <summary>
        /// update document data
        /// </summary>
        private void UpdateDocument(string Note, string Author, string CreditPhoto)
        {
            DesactivatePanel();
            m_iCounterUpdateOk = 0;
            m_iCounterUpdateKO = 0;

            try
            {
                //if several documents are selected (in mode thumbnail only)
                if ((SelectedDocumentsFromThumbnails != null) && (SelectedDocumentsFromThumbnails.Count > 0))
                {
                    MessageBoxChildWindow L_oMessageConfirmation = new MessageBoxChildWindow("", m_szOverwriteConfirmation, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    L_oMessageConfirmation.Closed += (s, ev) =>
                    {
                        if (L_oMessageConfirmation.Result == MessageBoxResult.Yes)
                        {
                            m_iActivePanel = SelectedDocumentsFromThumbnails.Count;
                            foreach (Document doc in SelectedDocumentsFromThumbnails)
                            {
                                BusinessEntitiesDomainContext businessEntitiesDomainContext = GlobalWebContext.BusinessEntitiesDomainContext;
                                var query = businessEntitiesDomainContext.UpdateDocumentQuery(doc.FolderTypeIdentifier, doc.FolderId, doc.Identifier, Note.Trim(), Author.Trim(), CreditPhoto.Trim());
                                businessEntitiesDomainContext.Load(query, OnUpdateDocumentCallback, null);
                            }
                        }
                        else
                        {
                            ActivatePanel();
                        }
                    };

                    L_oMessageConfirmation.ShowDialog();
                }
                //else if one document is selected (in mode thumbnail and viewer)
                else if (CurrentDocument != null)
                {
                    m_iActivePanel = 1;
                    BusinessEntitiesDomainContext businessEntitiesDomainContext = GlobalWebContext.BusinessEntitiesDomainContext;
                    var query = businessEntitiesDomainContext.UpdateDocumentQuery(CurrentDocument.FolderTypeIdentifier, CurrentDocument.FolderId, CurrentDocument.Identifier, Note.Trim(), Author.Trim(), CreditPhoto.Trim());
                    businessEntitiesDomainContext.Load(query, OnUpdateDocumentCallback, null);
                }
                else
                {
                    //Re Activate panel if no action
                    ActivatePanel();
                }
            }
            catch (Exception)
            {
                ActivatePanel();
                MessageBoxChildWindow L_oMessage = new MessageBoxChildWindow("", m_szUpdateFailed, MessageBoxButtons.Ok, MessageBoxIcon.Warning);
                L_oMessage.ShowDialog();
            }
        }
        private void OnUpdateDocumentCallback(LoadOperation result)
        {
            if (result.HasError)
            {
                m_iCounterUpdateKO++;
                Logger.Write("EXCEPTION : " + Environment.NewLine + result.Error.Message, Logger.Level.Error);
            }
            else
            {
                m_iCounterUpdateOk++;
            }

            //Active the Panel
            m_iActivePanel--;
            if (m_iActivePanel == 0)
            {
                ActivatePanel();

                MessageBoxChildWindow message = new MessageBoxChildWindow("", String.Format(m_szLabelUpdate, m_iCounterUpdateOk, m_iCounterUpdateKO), MessageBoxButtons.Ok, MessageBoxIcon.Information);
                message.Closed += delegate
                {
                    if (message.DialogResult == true)
                    {
                        //refresh
                        LoadFolderDocument(null);
                    }
                };
                message.ShowDialog();
            }
        }

        private void UpdateDocumentItem()
        {
            try
            {
                DesactivatePanel();
                m_iCounterUpdateOk = 0;
                m_iCounterUpdateKO = 0;

                if ((TreeViewControlItems != null) && (SelectedItem != null))
                {

                    CursorHand(this);
                    DataItemTreeView l_oDataItemTreeView = SelectedItem;

                    //if several documents are selected (in mode thumbnail only)
                    if ((SelectedDocumentsFromThumbnails != null) && (SelectedDocumentsFromThumbnails.Count > 0) &&
                        (DisplayMode == SelectModeDocument.Thumbnail || DisplayMode == SelectModeDocument.List))
                    {
                        m_iActivePanel = SelectedDocumentsFromThumbnails.Count;

                        foreach (Document doc in SelectedDocumentsFromThumbnails)
                        {
                            BusinessEntitiesDomainContext businessEntitiesDomainContext = GlobalWebContext.BusinessEntitiesDomainContext;
                            var query = businessEntitiesDomainContext.UpdateDocumentItemQuery(doc.FolderTypeIdentifier, CurrentFolder.Identifier, doc.Identifier, l_oDataItemTreeView.Code);
                            SelectedItem = m_oPreviousSelectedItem;
                            SelectedItem = m_oPreviousSelectedItem;
                            businessEntitiesDomainContext.Load(query, OnUpdateDocumentItemCallback, null);
                        }
                    }
                    //else if one document is selected (in mode thumbnail and viewer)
                    else if (CurrentDocument != null && DisplayMode == SelectModeDocument.Viewer)
                    {
                        m_iActivePanel = 1;
                        BusinessEntitiesDomainContext businessEntitiesDomainContext = GlobalWebContext.BusinessEntitiesDomainContext;
                        var query = businessEntitiesDomainContext.UpdateDocumentItemQuery(CurrentDocument.FolderTypeIdentifier, CurrentFolder.Identifier, CurrentDocument.Identifier, l_oDataItemTreeView.Code);
                        SelectedItem = m_oPreviousSelectedItem;
                        businessEntitiesDomainContext.Load(query, OnUpdateDocumentItemCallback, null);
                    }
                    else
                    {
                        CursorNormal(this);
                        ActivatePanel();
                    }
                }
                else
                {
                    MessageBoxChildWindow L_oMessage = new MessageBoxChildWindow("", m_szUpdateFailed, MessageBoxButtons.Ok, MessageBoxIcon.Warning);
                    L_oMessage.ShowDialog();
                }
            }
            catch (Exception)
            {
                ActivatePanel();
                MessageBoxChildWindow L_oMessage = new MessageBoxChildWindow("", m_szUpdateFailed, MessageBoxButtons.Ok, MessageBoxIcon.Warning);
                L_oMessage.ShowDialog();
            }
        }

        /// <summary>
        /// event to update item's document
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void buttonUpdateDocumentItem_Click(object sender, RoutedEventArgs e)
        {
            UpdateDocumentItem();
        }

        /// <summary>
        /// Called when [update document item callback].
        /// </summary>
        /// <param name="result">The result.</param>
        private void OnUpdateDocumentItemCallback(LoadOperation result)
        {
            CursorNormal(this);

            if (result.HasError)
            {
                m_iCounterUpdateKO++;
                Logger.Write("EXCEPTION : " + Environment.NewLine + result.Error.Message, Logger.Level.Error);
            }
            else
            {
                OnDataHasChanged();
                m_iCounterUpdateOk++;
            }

            //Active the Panel
            m_iActivePanel--;
            if (m_iActivePanel == 0)
            {
                ActivatePanel();
                MessageBoxChildWindow message = new MessageBoxChildWindow("", String.Format(m_szLabelUpdate, m_iCounterUpdateOk, m_iCounterUpdateKO), MessageBoxButtons.Ok, MessageBoxIcon.Information);
                message.Closed += delegate
                {
                    if (message.DialogResult == true)
                    {
                        LoadFolderDocument(null);
                        AddOrRefreshTrashItemInTreeView();
                    }
                };
                message.ShowDialog();
            }
        }

        /// <summary>
        /// Called when [add document event].
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.EventArgs" /> instance containing the event data.</param>
        private void OnAddDocumentEvent(object sender, EventArgs e)
        {
            AddDocumentChildWindow l_oAddDocument = new AddDocumentChildWindow(
                CurrentFolderType,
                CurrentOrganization,
                CurrentFolder,
                Int32.Parse(GlobalWebContext.RioAppSettings["MaxNumberOfFilesImported"]))
            {
                Width = ActualWidth,
                Height = ActualHeight
            };

            l_oAddDocument.Closed += l_oAddDocument_Closed;
            l_oAddDocument.ShowDialog();
        }

        /// <summary>
        /// Handles the Closed event of the l_oAddDocument control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs" /> instance containing the event data.</param>
        private void l_oAddDocument_Closed(object sender, EventArgs e)
        {
            AddDocumentChildWindow l_oAddDocWin = (AddDocumentChildWindow)sender;
            if (l_oAddDocWin.DialogResult == true)
            {
                this.LoadDocumentsFolder();
                OnDataHasChanged();
            }
            l_oAddDocWin.Closed -= l_oAddDocument_Closed;
        }

        /// <summary>
        /// Event to update index folder
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void buttonUpdateIndex_Click(object sender, RoutedEventArgs e)
        {
            if (((Button)sender).Content.Equals(m_sLabelButtonModifyIndex))
            {
                foreach (var item in StackIndex.CriteriaControls)
                {
                    if (item.GetType().Equals(typeof(TextIndexControl)))
                    {
                        Index L_oIndex = ((TextIndexControl)item).CurrentIndex;

                        if (L_oIndex.Type == (int)IndexDomainServiceEnums.IndexType.TypeChrono)
                        {
                            //Disable Chrono index
                            ((TextIndexControl)item).IsEnabled = false;
                        }
                    }
                    else if (item.GetType().Equals(typeof(ListGroupIndexControl)))
                    {
                        Index L_oIndex = ((ListGroupIndexControl)item).CurrentIndex;

                        if (L_oIndex.Type == (int)IndexDomainServiceEnums.IndexType.ListeOfRecipient)
                        {
                            //Disable list of receiver if we have an attached workflow
                            var query = GetDataContext.GetWorkflowInstancesByFolderIdQuery(
                                CurrentFolderType.Identifier,
                                CurrentFolder.Identifier,
                                GlobalWebContext.CurrentUser.UserId,
                                GlobalWebContext.GetIsAdministrator(CurrentFolderType));

                            GetDataContext.Load<WorkflowInstance>(
                                query,
                                result =>
                                {
                                    if (!result.HasError &&
                                        result.Entities != null)
                                    {
                                        if (result.Entities.Any(wkf => !wkf.IsEnded))
                                        {
                                            ((ListGroupIndexControl)result.UserState).IsEnabled = false;
                                        }
                                    }
                                },
                                item);
                        }
                    }
                }

                SwitchIndexButtonVisibility(true);
            }
            else
            {
                UpdateFolder();
            }
        }

        #endregion

        #region Folder Comment

        /// <summary>
        /// Opens the comment window.
        /// </summary>
        private void OpenCommentWindow(bool isInit = false)
        {
            if (CurrentFolder == null)
            {
                return;
            }

            if (String.IsNullOrWhiteSpace(FolderComment))
            {
                FolderComment = CurrentFolder.Note;
            }

            if (CommentChildWindow == null)
                CommentChildWindow = new CommentChildWindow
                {
                    Header = Resx.GetLabel(ResxFolderPage.FOLDER_COMMENT),
                    Comment = FolderComment,
                    IsReadOnly = !m_bCanModify
                };

            bool openWindow = false;

            if ((isInit && !String.IsNullOrWhiteSpace(FolderComment)))
                openWindow = true;

            if (!CommentChildWindow.IsOpen && !isInit)
                openWindow = true;

            if (openWindow)
            {
                /*
                * The Popup is opened if :
                *  1. We are at the initialization of FolderPage (when the folder is loaded) and there is a comment (not empty)
                *          -- OR --
                *  2. We click on the button
                */

                CommentChildWindow.Closed += CommentChildWindowClosed;
                CommentChildWindow.Visibility = Visibility.Visible;
                CommentChildWindow.MustBeOpen = true;
                CommentChildWindow.Show();
            }
        }

        private void CommentChildWindowClosed(object sender, WindowClosedEventArgs e)
        {
            CommentChildWindow commentChildWindowSource = sender as CommentChildWindow;
            if (commentChildWindowSource != null)
            {
                commentChildWindowSource.Closed -= CommentChildWindowClosed;

                CommentChildWindow.MustBeOpen = false;

                if (commentChildWindowSource.DialogResult == true)
                {
                    string newComment = commentChildWindowSource.Comment;

                    //Save new comment
                    if (FolderComment != newComment)
                    {
                        FolderComment = newComment;

                        BusinessEntitiesDomainContext businessEntitiesDomainContext = GlobalWebContext.BusinessEntitiesDomainContext;
                        var query = businessEntitiesDomainContext.UpdateFolderCommentQuery(CurrentFolderType.Identifier, CurrentFolder.Identifier, CurrentFolder.Iddoc, FolderComment);
                        businessEntitiesDomainContext.Load(query, UpdateFolderCommentQueryCallback, null);
                    }
                }
            }
        }

        /// <summary>
        /// Call back of the UpdateFolderCommentQuery action
        /// </summary>
        /// <param name="p_oResult"></param>
        private void UpdateFolderCommentQueryCallback(LoadOperation p_oResult)
        {
            if (p_oResult.HasError)
            {
                MessageBoxChildWindow L_oMessage = new MessageBoxChildWindow(String.Empty, Resx.GetLabel(ResxFolderPage.COMMENT_ERROR), MessageBoxButtons.Ok, MessageBoxIcon.Information);
                L_oMessage.ShowDialog();
            }
            else
            {
                OnDataHasChanged();
            }
        }

        #endregion

        #region Folder Rights

        /// <summary>
        /// Folder right managment click.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void ManageFolderRightClick(object sender, RoutedEventArgs e)
        {
            FolderAdministrationWindow L_oFolderAdministrationWindow = new FolderAdministrationWindow(CurrentFolderType, CurrentFolder);
            L_oFolderAdministrationWindow.Header = m_sLabelButtonManageFolderRights;
            L_oFolderAdministrationWindow.ShowDialog();
        }

        #endregion

        #region Folder informations

        /// <summary>
        /// Manages the folder informations 
        /// </summary>
        private void ManageFolderInformations()
        {
            if (CurrentDocument != null)
            {
                if (CurrentSelectedVersion == null)
                {
                    //GRY
                    //RadExpanderDocument.Header = CurrentDocument.OriginalNameFile;
                }
                else
                {
                    //GRY
                    //RadExpanderDocument.Header = string.Format("{0}, version:{1}.{2}", CurrentDocument.OriginalNameFile, _currentVersion.Major, _currentVersion.Minor);
                }

                if (CurrentDocument.Author.Equals(String.Empty) && CurrentDocument.Note.Equals(String.Empty))
                {
                    UpdateDocumentBarItemStyle(false);
                }
                else
                {
                    UpdateDocumentBarItemStyle(true);
                }

                //Abo documentBarItem in Yellow if document with an comment. 
                RadOutlookBarDocumentItemColorBackground = (!CurrentDocument.Note.Equals(string.Empty))
                                             ? new SolidColorBrush(Color.FromArgb(255, 255, 255, 0))
                                             : new SolidColorBrush(Color.FromArgb(0, 0, 0, 0));
            }
        }

        #endregion

        #region Trash

        /// <summary>
        /// Handles the Click event of the buttonRestoreDocuments control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void ButtonRestoreDocumentsClick(object sender, RoutedEventArgs e)
        {
            m_oSplashScreen.Show();
            ModalControls.ModalDialogController.Launch(m_oSplashScreen);

            //if several documents are selected (in mode thumbnail only)
            if (DisplayMode != SelectModeDocument.Viewer && (SelectedDocumentsFromThumbnails != null) && (SelectedDocumentsFromThumbnails.Count > 0))
            {
                BusinessEntitiesDomainContext businessEntitiesDomainContext = GlobalWebContext.BusinessEntitiesDomainContext;
                businessEntitiesDomainContext.RestoreDocument(
                    SelectedDocumentsFromThumbnails.Select(document => document.Identifier),
                    RestoreDocumentCallback,
                    null);
            }
            //else if one document is selected (in mode thumbnail and viewer)
            else if (CurrentDocument != null)
            {
                List<long> list = new List<long> { CurrentDocument.Identifier };
                BusinessEntitiesDomainContext businessEntitiesDomainContext = GlobalWebContext.BusinessEntitiesDomainContext;
                businessEntitiesDomainContext.RestoreDocument(list,
                    RestoreDocumentCallback,
                    null);
            }
            else
            {
                m_oSplashScreen.Close();
            }
        }

        /// <summary>
        /// Restores the document callback.
        /// </summary>
        /// <param name="result">The result.</param>
        private void RestoreDocumentCallback(InvokeOperation<ReturnBoolean> result)
        {
            AddOrRefreshTrashItemInTreeView();

            LoadDocumentsFolder();

            LoadTrashDocuments();

            DataItemTreeView trashItem = TreeViewControlItems.ItemsList.Single(item => item.IsTrashItem);
            SelectedItem = trashItem;

            m_oSplashScreen.Close();
            OnDataHasChanged();
        }

        /// <summary>
        /// Loads the trash documents.
        /// </summary>
        private void LoadTrashDocuments()
        {
            //Load Trash documents
            BusinessEntitiesDomainContext businessEntitiesDomainContext = GlobalWebContext.BusinessEntitiesDomainContext;

            var getDeletedDocumentsQuery = businessEntitiesDomainContext.GetDeletedDocumentsQuery(CurrentFolderType.Identifier, CurrentFolder.Identifier);

            businessEntitiesDomainContext.Load(
                getDeletedDocumentsQuery,
                GetDeletedDocumentsQueryCallBack,
                null);
        }

        /// <summary>
        /// Gets the deleted documents query call back.
        /// </summary>
        /// <param name="result">The result.</param>
        private void GetDeletedDocumentsQueryCallBack(LoadOperation<Document> result)
        {
            UpdateListDocumentFromSelectedItem(new List<Document>(result.Entities));
            
            buttonRestoreDocuments.IsEnabled = result.Entities.Count() > 0 && m_bCanTrash;

            //Used to select the first document 
            UCViewerCore viewer = GetCurrentViewer();
            viewer.SelectedDocumentIndex = 0;

            if (CurrentDocument != null)
            {
                ManageFolderInformations();
            }
        }

        #endregion

        #region Versioning

        /// <summary>
        /// Version created successfully.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void versioningManager_VersionCreated(object sender, VersioningEventArgs args)
        {
            this.Cursor = Cursors.Arrow;
            SplashScreenManager.Stop(this);
            CurrentSelectedVersion = args.item;
            LoadFolderDocument(null);
        }

        /// <summary>
        /// Version creation error.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void versioningManager_CreationError(object sender, VersioningEventArgs e)
        {
            SplashScreenManager.Stop(this);
            MessageBoxChildWindow L_oMessageGetDocument = new MessageBoxChildWindow("Versioning error", e.Error, MessageBoxButtons.Ok, MessageBoxIcon.Error);
            L_oMessageGetDocument.ShowDialog();
        }

        /// <summary>
        /// Make this version to major process handler.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void m_oViewerControl_MakeThisVersionToMajorClick(object sender, EventArgs e)
        {
            CreateNewVersionClick();
        }

        /// <summary>
        /// Create new version handler.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void m_oViewerControl_CreateNewVersionClick(object sender, EventArgs e)
        {
            MakeThisVersionToMajorClick(CurrentSelectedVersion);
        }

        /// <summary>
        /// Create new version
        /// </summary>
        private void CreateNewVersionClick()
        {
            if (CurrentDocument != null)
            {
                BusinessEntitiesDomainContext businessEntitiesDomainContext = GlobalWebContext.BusinessEntitiesDomainContext;

                //Check if the document have checkouted version 
                businessEntitiesDomainContext.GetCurrentVersion(CurrentDocument.Identifier,
                    delegate(InvokeOperation<VersioningItem> retr)
                    {
                        if (retr != null && retr.Value != null && retr.Value.IsValid)
                        {
                            var version = retr.Value;
                            if (version.State == VersionState.Checkout)
                            {
                                //document is checkouted!
                                MessageBoxChildWindow L_oMessage = new MessageBoxChildWindow("", string.Format(m_szMsgDocumentInCheckout + " (Version={1})", version.CreatedBy, version.VersionId), MessageBoxButtons.Ok, MessageBoxIcon.Warning);
                                L_oMessage.ShowDialog();
                            }
                            else
                            {
                                //show add version child window
                                AddDocumentVersionChildWindow addDocumentVersionChildWindow = new AddDocumentVersionChildWindow(CurrentDocument)
                                {
                                    Versions = new ObservableCollection<VersioningItem>(CurrentDocument.AllVersion),
                                    CurrentVersionType = CurrentDocument.CurrentModelVersion.ModelType,
                                };
                                addDocumentVersionChildWindow.Closed += delegate
                                {
                                    if (addDocumentVersionChildWindow.DialogResult == true)
                                    {
                                        SplashScreenManager.Wait(this);
                                        if (addDocumentVersionChildWindow.CurrentVersionType == VersionType.NoControl && addDocumentVersionChildWindow.SelectedFile != null)
                                        {
                                            //In this mode the version must be overwrite
                                            this._versioningManager.OverwriteVersion(CurrentDocument.Identifier, addDocumentVersionChildWindow.SelectedFile);
                                        }
                                        else
                                        {
                                            //in all Other mode the version is added with major minor schéma
                                            if (addDocumentVersionChildWindow.UseSelectedFile && addDocumentVersionChildWindow.SelectedFile != null)
                                            {
                                                //Create version with new file
                                                this._versioningManager.AddVersionFromFile(CurrentDocument.Identifier, addDocumentVersionChildWindow.SelectedFile, CurrentDocument.CurrentModelVersion.Identifier, addDocumentVersionChildWindow.IsMajor);
                                            }
                                            else
                                            {
                                                //Create version form old version
                                                this._versioningManager.AddVersionFromOldVersion(CurrentDocument.Identifier, addDocumentVersionChildWindow.SelectedVersion, CurrentDocument.CurrentModelVersion.Identifier, addDocumentVersionChildWindow.IsMajor);
                                            }
                                        }
                                    }
                                };
                                addDocumentVersionChildWindow.ShowDialog();
                            }
                        }
                        else
                        {
                            if (retr != null && retr.Value != null)
                            {
                                //error
                                MessageBoxChildWindow L_oMessage = new MessageBoxChildWindow("", retr.Value.ErrorMessage, MessageBoxButtons.Ok, MessageBoxIcon.Error);
                                L_oMessage.ShowDialog();
                            }
                        }
                    }, null);
            }
        }

        /// <summary>
        /// Make this version to major.
        /// </summary>
        private void MakeThisVersionToMajorClick(VersioningItem currentVersion)
        {
            if (currentVersion != null)
            {
                BusinessEntitiesDomainContext businessEntitiesDomainContext = GlobalWebContext.BusinessEntitiesDomainContext;

                //Check if the document have checkouted version 
                businessEntitiesDomainContext.GetCurrentVersion(CurrentDocument.Identifier,
                    delegate(InvokeOperation<VersioningItem> retr)
                    {
                        if (retr != null && retr.Value != null && retr.Value.IsValid)
                        {
                            var version = retr.Value;
                            if (version.State == VersionState.Checkout)
                            {
                                //document checkouted
                                MessageBoxChildWindow L_oMessage = new MessageBoxChildWindow("", string.Format(m_szMsgDocumentInCheckout + " (Version={1})", version.CreatedBy, version.VersionId), MessageBoxButtons.Ok, MessageBoxIcon.Warning);
                                L_oMessage.ShowDialog();
                            }
                            else
                            {
                                MessageBoxChildWindow confirmMessageBox = new MessageBoxChildWindow(
                                    Resx.GetLabel(ResxFolderPage.NEW_MAJOR_VERSION_TITLE),
                                    Resx.GetLabel(ResxFolderPage.NEW_MAJOR_VERSION_BODY),
                                    MessageBoxButtons.YesNo,
                                    MessageBoxIcon.Question);
                                confirmMessageBox.Closed += delegate
                                {
                                    if (confirmMessageBox.DialogResult == true)
                                    {
                                        SplashScreenManager.Wait(this);
                                        this._versioningManager.AddVersionFromOldVersion(CurrentDocument.Identifier, currentVersion, CurrentDocument.CurrentModelVersion.Identifier, true);
                                    }
                                };
                                confirmMessageBox.ShowDialog();
                            }
                        }
                        else
                        {
                            if (retr != null && retr.Value != null)
                            {
                                //error
                                MessageBoxChildWindow L_oMessage = new MessageBoxChildWindow("", retr.Value.ErrorMessage, MessageBoxButtons.Ok, MessageBoxIcon.Error);
                                L_oMessage.ShowDialog();
                            }
                        }
                    }, null);
            }
        }

        /// <summary>
        /// Make this version to major.
        /// </summary>
        private void CheckOutClick(VersioningItem currentVersion)
        {
            String l_sDocumentPath = string.Empty;
            if (currentVersion != null) l_sDocumentPath = Path.Combine(currentVersion.DocumentPath);
            else l_sDocumentPath = Path.Combine(CurrentDocument.RelativePath, CurrentDocument.ImageName);

            this.dialog.DefaultFileName = Path.GetFileName(l_sDocumentPath);

            bool? dialogResult = this.dialog.ShowDialog();

            if (dialogResult == true)
            {
                try
                {
                    WCFService.RioWcfServices.WCFServiceClient l_oWCFServiceClient = WCFService.ServiceManager.GetRioWCFServiceClient();
                    l_oWCFServiceClient.GetFileByFullPathCompleted += l_oWCFServiceClient_GetFileByFullPathCompleted;


                    l_oWCFServiceClient.GetFileByFullPathAsync(
                        Path.Combine(GlobalWebContext.ParameterStorage, l_sDocumentPath),
                        Rio.Framework.WCFService.ServiceManager.GetLicenseKey(),
                        GlobalWebContext.CurrentUser.UserId);
                }
                catch
                {
                }
            }
        }

        /// <summary>
        /// Handles the GetFileByFullPathCompleted event of the l_oWCFServiceClient control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Rio.Framework.WCFService.RioWcfServices.GetFileByFullPathCompletedEventArgs"/> instance containing the event data.</param>
        private void l_oWCFServiceClient_GetFileByFullPathCompleted(object sender, Rio.Framework.WCFService.RioWcfServices.GetFileByFullPathCompletedEventArgs e)
        {
            try
            {
                byte[] fileBytes = e.Result.Value as byte[];
                using (Stream fs = (Stream)this.dialog.OpenFile())
                {
                    fs.Write(fileBytes, 0, fileBytes.Length);
                    fs.Close();
                }
            }
            catch
            {
            }
        }

        /// <summary>
        /// Loads the selected version.
        /// </summary>
        private void LoadSelectedVersion()
        {
            if (CurrentSelectedVersion != null)
            {
                DisplayMode = SelectModeDocument.Viewer;
                m_oViewerControl.Visibility = Visibility.Visible;
                m_oListVignetteSearch.Visibility = System.Windows.Visibility.Collapsed;
                m_oListViewer.Visibility = System.Windows.Visibility.Collapsed;

                int selectedDocumentIndex = 0;
                if (CurrentDocument != null)
                {
                    selectedDocumentIndex = m_oListSelectedDocumentFromItem.IndexOf(CurrentDocument);
                }
                m_oViewerControl.LoadSpecificVersion(CurrentSelectedVersion, selectedDocumentIndex);
                if (CurrentSelectedVersion.IsCurrentVersion)
                {
                    ManageConsultationMode(AppCode.Enums.ConsultationModeType.Disable);
                }
                else
                {
                    ManageConsultationMode(AppCode.Enums.ConsultationModeType.OldVersion);
                }
            }
        }

        #endregion

        #region Copy-Cut-Paste

        /// <summary>
        /// Reload Paste Menu visibility
        /// </summary>
        public void ReloadPasteMenuVisibility()
        {
            switch (DisplayMode)
            {
                case SelectModeDocument.List:
                    if (m_oListViewer != null)
                    {
                        m_oListViewer.DocumentContextMenu.ManageContextMenuItemState();
                        m_oListViewer.DocumentToolbar.ManageToolbar();
                    }
                    break;
                case SelectModeDocument.Thumbnail:
                    if (m_oListVignetteSearch != null)
                    {
                        m_oListVignetteSearch.DocumentContextMenu.ManageContextMenuItemState();
                        m_oListVignetteSearch.DocumentToolbar.ManageToolbar();
                    }
                    break;
                case SelectModeDocument.Viewer:
                    if (m_oViewerControl != null)
                    {
                        m_oViewerControl.DocumentContextMenu.ManageContextMenuItemState();
                        m_oViewerControl.DocumentToolbar.ManageToolbar();
                    }
                    break;
            }
        }

        /// <summary>
        /// Handles the DocumentCopiedOrCuted event raised by UCViewer, Thumbnail or ListViewer control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void CopyPasteDocumentsHandle(object sender, PasteCopyEventArgs e)
        {
            switch (e.Action)
            {
                case PasteCopyActionType.Copy:
                    OnDocumentCopiedOrCut(e.Action, CurrentFolder);
                    ReloadPasteMenuVisibility();
                    break;
                case PasteCopyActionType.Cut:
                    e.SourceFolder = CurrentFolder;
                    CutDocuments(e);
                    break;
                case PasteCopyActionType.Paste:
                    e.SourceFolder = CurrentFolder;
                    PasteDocuments(e);
                    break;
            }
        }

        /// <summary>
        /// Cuts the documents.
        /// </summary>
        private void CutDocuments(PasteCopyEventArgs e)
        {
            List<long> documentsIds = new List<long>();
            switch (DisplayMode)
            {
                case SelectModeDocument.Thumbnail:
                    documentsIds = _selectedDocumentsFromThumbnails.Select(p => p.Identifier).ToList();
                    break;
                case SelectModeDocument.Viewer:
                    documentsIds = new List<long>() {CurrentDocument.Identifier};
                    break;
                case SelectModeDocument.List:
                    documentsIds = _selectedDocumentsFromThumbnails.Select(p => p.Identifier).ToList();
                    break;
            }

            BusinessEntitiesDomainContext businessEntitiesDomainContext = GlobalWebContext.BusinessEntitiesDomainContext;
            businessEntitiesDomainContext.GetDocumentsIdsInWorkfow(documentsIds, GetWorkflowInstanceByDocumentsIdCallback, e);
        }

        /// <summary>
        /// Gets the workflow instance by documents id callback.
        /// </summary>
        /// <param name="invokeOperation">The invoke operation.</param>
        private void GetWorkflowInstanceByDocumentsIdCallback(InvokeOperation<IEnumerable<long>> invokeOperation)
        {
            if (invokeOperation.HasError)
            {
                MessageBoxChildWindow L_oMessage = new MessageBoxChildWindow("", invokeOperation.Error.Message, MessageBoxButtons.Ok, MessageBoxIcon.Error);
                L_oMessage.ShowDialog();
            }
            else
            {
                List<long> result = new List<long>(invokeOperation.Value);
                if (result.Count > 0)
                {
                    MessageBoxChildWindow L_oMessage = new MessageBoxChildWindow("", "Un ou des documents n'ont pas pu être ajoutés au presse papier car ils sont rattachés à un flux en cours!", MessageBoxButtons.Ok,
                                                                                 MessageBoxIcon.Warning);
                    L_oMessage.ShowDialog();

                    //Remove all documents 
                    for (int i = 0; i < result.Count; i++)
                    {
                        if (GlobalWebContext.CopyPasteManager.Documents.Contains(result[i]))
                        {
                            GlobalWebContext.CopyPasteManager.RemoveDocument(result[i]);
                        }
                    }
                    ReloadPasteMenuVisibility();

                    //Refresh copy paste selection from 
                    var viewer = GetCurrentViewer();
                    if(viewer != null)
                    {
                        viewer.UpdateCopyPasteSelection();
                    }
                }

                //Raise event
                OnDocumentCopiedOrCut(PasteCopyActionType.Cut, null);
            }
        }

        /// <summary>
        /// Paste all documents contained in clipboard inside the selected item and current folder
        /// </summary>
        private void PasteDocuments(PasteCopyEventArgs e)
        {
            if (CurrentFolder != null)
            {
                // Unauthorized access
                if (SelectedItem != null && (SelectedItem.IsTrashItem || !SelectedItem.CanBeModify))
                {
                    MessageBoxChildWindow L_oMessage = new MessageBoxChildWindow("", Resx.GetLabel(ResxFolderPage.MSG_UNAUTHORIZED_PASTE), MessageBoxButtons.Ok, MessageBoxIcon.Warning);
                    L_oMessage.ShowDialog();
                    return;
                }

                // Item rank
                string selectedRank = null;
                if (SelectedItem != null)
                {
                    selectedRank = SelectedItem.Code;
                }

                BusinessEntitiesDomainContext businessEntitiesDomainContext = GlobalWebContext.BusinessEntitiesDomainContext;
                if (GlobalWebContext.CopyPasteManager.ActionType == PasteCopyActionType.Cut)
                {
                    m_oSplashScreen.Show();
                    Framework.Pages.ModalControls.ModalDialogController.Launch(m_oSplashScreen);

                    //Call Cut-Past service
                    businessEntitiesDomainContext.PasteDocument(GlobalWebContext.CopyPasteManager.Documents, CurrentFolder.Iddoc, CurrentFolder.Identifier, CurrentFolderType.Identifier, true, selectedRank,
                        GlobalWebContext.CopyPasteManager.VersionIdentifier, GlobalWebContext.CopyPasteManager.IsOriginalVersion, PasteDocumentsQueryCallback, null);
                }
                else if (GlobalWebContext.CopyPasteManager.ActionType == PasteCopyActionType.Copy)
                {
                    m_oSplashScreen.Show();
                    Framework.Pages.ModalControls.ModalDialogController.Launch(m_oSplashScreen);

                    //Call Copy-Past service
                    businessEntitiesDomainContext.PasteDocument(GlobalWebContext.CopyPasteManager.Documents, CurrentFolder.Iddoc, CurrentFolder.Identifier, CurrentFolderType.Identifier, false, selectedRank,
                        GlobalWebContext.CopyPasteManager.VersionIdentifier, GlobalWebContext.CopyPasteManager.IsOriginalVersion, PasteDocumentsQueryCallback, null);
                }
            }
        }

        /// <summary>
        /// PasteDocuments Callback, clear clipborad then reload folder
        /// </summary>
        /// <param name="e">The e.</param>
        private void PasteDocumentsQueryCallback(InvokeOperation<ReturnBoolean> e)
        {
            if (!e.HasError && e.Value != null && e.Value.Value)
            {
                LoadFolderDocument();

                var sourceFolder = GlobalWebContext.CopyPasteManager.SourceFolder;
                GlobalWebContext.CopyPasteManager.ClearDocuments();
                ReloadPasteMenuVisibility();

                OnDocumentCopiedOrCut(PasteCopyActionType.Paste, sourceFolder);
                OnDataHasChanged();
            }
            GlobalWebContext.CopyPasteManager.ClearDocuments();
        }

        #endregion

        #region Historic

        /// <summary>
        /// Adds the historic consultation : when a folder is open.
        /// </summary>
        private void AddHistoricConsultation()
        {
            //Create list of IndexValue + IndexId + IndexLabel
            List<HistoricIndex> historicIndexList = new List<HistoricIndex>();

            CurrentFolder.ListIndex.ToList().ForEach(
                index => historicIndexList.Add(new HistoricIndex()
                {
                    IndexId = index.Indentifier,
                    IndexLabel = index.IndexLabel,
                    IndexValue = GetDisplayIndexValue(CurrentFolder.ListValues.ToList()[CurrentFolder.ListIndex.ToList().IndexOf(index)])
                }));

            //Seralize list
            string historicIndexListSerialized = SerializationHelper.Serialize<List<HistoricIndex>>(historicIndexList);

            BusinessEntitiesDomainContext businessEntitiesDomainContext = GlobalWebContext.BusinessEntitiesDomainContext;
            var query = businessEntitiesDomainContext.AddHistoricInfoConsultQuery(
                (int)Constant.UserActions.CONSULTATION_DOSSIER,
                CurrentFolderType.Identifier,
                CurrentFolder.Identifier,
                CurrentFolder.Iddoc,
                null,
                null,
                historicIndexListSerialized,
                false,
                CurrentFolder.NbDoc,
                0,
                0,
                null);

            businessEntitiesDomainContext.Load(query);
        }

        #endregion

        #region Functions

        /// <summary>
        /// Gets the current viewer instance.
        /// </summary>
        /// <returns></returns>
        private UCViewerCore GetCurrentViewer()
        {
            switch (DisplayMode)
            {
                case SelectModeDocument.Thumbnail:
                    return m_oListVignetteSearch;
                case SelectModeDocument.Viewer:
                    return m_oViewerControl;
                case SelectModeDocument.List:
                    return m_oListViewer;
                default:
                    return null;
            }
        }

        /// <summary>
        /// Manages consultation mode
        /// </summary>
        /// <param name="modeToApply">The mode to apply.</param>
        private void ManageConsultationMode(ConsultationModeType modeToApply)
        {
            /****************************************************
             * This method manages the visibility of control on this page.
             * The consultation mode must be set when :
             * - Trash item is selected (trash mode),
             * - One item is selected (disabled mode),
             * - Old document version is displayed (OldVersion mode),
             * - The default mode is disabled for displaying document in classical item
             * 
             * She does take account of the display mode :
             * - In search mode, the above rule is applied with no restriction
             * - In flow mode only the trash item is applied, all other modes are not availables
             * 
             * *****************************************************/

            if (AppDisplayMode == AppDisplayMode.Search)
            {
                //Apply correct mode
                switch (modeToApply)
                {
                    case ConsultationModeType.Disable:
                        ConsultationModeType = modeToApply;
                        EnableDisableConsultationMode(ConsultationModeType);

                        break;
                    case ConsultationModeType.Workflow:
                        ConsultationModeType = modeToApply;
                        EnableDisableConsultationMode(ConsultationModeType);

                        break;
                    case ConsultationModeType.Trash:
                        ConsultationModeType = modeToApply;
                        EnableDisableConsultationMode(ConsultationModeType);

                        break;
                    case ConsultationModeType.OldVersion:
                        ConsultationModeType = modeToApply;
                        EnableDisableConsultationMode(ConsultationModeType);

                        break;
                }

            }
            else if (AppDisplayMode == AppDisplayMode.Flow)
            {
                //Apply correct mode
                switch (modeToApply)
                {
                    case ConsultationModeType.Trash:
                        ConsultationModeType = modeToApply;
                        EnableDisableConsultationMode(ConsultationModeType);
                        break;

                    default:
                        ConsultationModeType = ConsultationModeType.Workflow;
                        EnableDisableConsultationMode(ConsultationModeType);
                        break;
                }
            }

        }

        /// <summary>
        /// Inits the label.
        /// </summary>
        public sealed override void InitLabel()
        {
            documentPropertiesLabel.Text = Resx.GetLabel(ResxFolderPage.INFO_DOCUMENT);
            versionningLabel.Text = Resx.GetLabel(ResxFolderPage.VERSION_MANAGE_CATEGORY_TITLE);

            indexBarItem.Header = Resx.GetLabel(ResxFolderPage.INDEX_TAB_HEADER);
            itemsBarItem.Header = Resx.GetLabel(ResxFolderPage.ITEMS);
            folderBarItem.Header = Resx.GetLabel(ResxFolderPage.FOLDER);
            documentBarItem.Header = Resx.GetLabel(ResxCommon.DOCUMENT_LABEL).Trim(' ', ':');

            folderHistoricLabel.Text = Resx.GetLabel(ResxWorkflow.Folder_Historic);

            buttonUpdateDocumentItem.Content = Resx.GetLabel(ResxFolderPage.RANK);

            labelFolderComment.Text = Resx.GetLabel(ResxFolderPage.FOLDER_COMMENT);
            m_oSplashScreen.Message = Resx.GetLabel(ResxCommon.SPLASHSCREEN_MESSAGE);
            m_sLabelCantConsult = Resx.GetLabel(ResxFolderPage.CANTCONSULT_MESSAGE);
            buttonCancelUpdateIndex.Content = Resx.GetLabel(ResxCommon.CANCEL);

            m_sLabelButtonModifyIndex = Resx.GetLabel(ResxFolderPage.UPDATEINDEX);
            m_sLabelButtonSaveIndex = Resx.GetLabel(ResxFolderPage.SAVEINDEX);
            m_szMsgNoUnicity = Resx.GetLabel(ResxIndexPanel.MSG_NO_UNICITY);
            m_szMsgFolderExist = Resx.GetLabel(ResxIndexPanel.MSG_FOLDER_EXIST);

            buttonRestoreDocuments.Content = Resx.GetLabel(ResxFolderPage.RESTORE_DOCUMENTS);

            buttonUpdateIndex.Content = m_sLabelButtonModifyIndex;
            m_sLabelButtonManageFolderRights = Resx.GetLabel(ResxFolderPage.MANAGE_FOLDER_RIGHTS);
            ManageFolderRightButtonText.Text = m_sLabelButtonManageFolderRights;

            m_szMsgDocumentInCheckout = Resx.GetLabel(ResxFolderPage.DOCUMENT_IS_IN_CHECKOUT_BY);

            #region Message box
            m_szUpdateValidation = Resx.GetLabel(ResxFolderPage.UPDATE_OK);
            m_szUpdateFailed = Resx.GetLabel(ResxFolderPage.UPDATE_FAILED);
            m_szMessageMandatoryField = Resx.GetLabel(ResxFolderPage.MANDATORYFIELD);
            m_szLabelUpdate = Resx.GetLabel(ResxFolderPage.UPDATE_OK_KO);
            m_szOverwriteConfirmation = Resx.GetLabel(ResxFolderPage.OVERWRITE_CONFIRMATION);
            #endregion
        }

        /// <summary>
        /// Activate the Panel
        /// </summary>
        public void ActivatePanel()
        {
            //GRY
            radOutlookBar.IsEnabled = true;
        }

        /// <summary>
        /// Desactive the Panel
        /// </summary>
        public void DesactivatePanel()
        {
            //GRY
            radOutlookBar.IsEnabled = false;
        }

        /// <summary>
        /// return a list of all documents fullname 
        /// ( this function enable to keep the order given by the user with the drag and drop)
        /// </summary>
        /// <returns></returns>
        public List<string> GetListFullNameItemDocument()
        {
            List<string> L_oListAllDocument = new List<string>();

            if (m_oListSelectedDocumentFromItem != null)
            {
                L_oListAllDocument.AddRange(m_oListSelectedDocumentFromItem.Select(doc => Path.Combine(doc.RelativePath, doc.ImageName)));
            }

            return L_oListAllDocument;
        }

        /// <summary>
        /// Passes the in consultation mode : disable all buttons.
        /// </summary>
        /// <param name="consultationModeType">Type of the consultation mode.</param>
        /// <param name="activateWorkflowActions">if set to <c>true</c> [activate workflow actions].</param>
        public void EnableDisableConsultationMode(ConsultationModeType consultationModeType = ConsultationModeType.Workflow)
        {
            /*
            * Left index panel
            */

            ManageFolderRightButton.IsEnabled = consultationModeType == ConsultationModeType.Disable;
            buttonUpdateDocumentItem.IsEnabled = consultationModeType == ConsultationModeType.Disable;
            buttonRestoreDocuments.IsEnabled = consultationModeType != ConsultationModeType.Workflow;

            /*
            * Viewers
            */

            if (m_oViewerControl != null)
            {
                m_oViewerControl.ChangeConsultationMode(CurrentOrganization, CurrentFolderType, consultationModeType, CurrentDocument != null && CurrentDocument.IsVersionable);
            }

            if (m_oListViewer != null)
            {
                m_oListViewer.ChangeConsultationMode(CurrentOrganization, CurrentFolderType, consultationModeType, CurrentDocument != null && CurrentDocument.IsVersionable);
            }

            if (m_oListVignetteSearch != null)
            {
                m_oListVignetteSearch.ChangeConsultationMode(CurrentOrganization, CurrentFolderType, consultationModeType, CurrentDocument != null && CurrentDocument.IsVersionable);
            }
        }

        #endregion

        #region Workflow

        private void WorkflowManagerFilterChanged(object sender, WorkflowState newState)
        {
            SplashScreenManager.Wait(this);

            LoadDocumentsFolder();
        }

        /// <summary>
        /// Loads the workflow.
        /// </summary>
        /// <param name="instance"></param>
        /// <param name="isSendMode"></param>
        public void LoadWorkflow(WorkflowInstance instance, bool isSendMode)
        {
            if (GlobalWebContext.LicenseTerms.LicenseType == LicenseType.Enterprise)
            {
                //Workflow manager
                if (instance != null)
                {
                    WorkflowManager.Initialize(instance, isSendMode);
                    WorkflowManager.Processing += WorkflowManagerProcessing;
                    WorkflowManager.Processed += WorkflowManagerProcessed;
                    WorkflowManager.PropertyChanged += WorkflowManagerPropertyChanged;

                    if (AppDisplayMode == AppDisplayMode.Flow)
                    {
                        LoadDocumentsFolder();
                    }

                    BusinessEntitiesDomainContext businessEntitiesDomainContext = GlobalWebContext.BusinessEntitiesDomainContext;
                    businessEntitiesDomainContext.WorkflowOpened(instance.DefinitionId);

                    if (m_oViewerControl != null)
                    {
                        m_oViewerControl.ChangeDisplayMode(AppDisplayMode.Flow);
                    }

                    ManageConsultationMode(ConsultationModeType.Workflow);

                    /*
                    * Workflow
                    */

                    Messenger.Default.Register<NotificationMessageAction<IndexedFilesEventArgs>>(
                        this,
                        instance.Identifier,
                        ActivateFlowIndexPanel);
                }
            }
            else
            {
                workflowToolbar.Visibility = Visibility.Collapsed;
            }
        }

        /// <summary>
        /// Manages the workflow menu.
        /// </summary>
        private void ManageWorkflowMenu()
        {
            if (IsWorkflowContext && _workflowManager.SelectedDocuments != null)
            {
                ReloadPasteMenuVisibility();
            }
        }

        /// <summary>
        /// Activates the flow index panel.
        /// </summary>
        /// <param name="notification">The notification.</param>
        private void ActivateFlowIndexPanel(NotificationMessageAction<IndexedFilesEventArgs> notification)
        {
            if (notification.Notification.ToLowerInvariant() == "activateflowindexpanel")
            {
                List<Document> selectedDocuments = new List<Document>();

                if (DisplayMode == SelectModeDocument.Viewer)
                {
                    selectedDocuments.Add(CurrentDocument);
                }
                else
                {
                    selectedDocuments.AddRange(SelectedDocumentsFromThumbnails);
                }

                if (selectedDocuments.Count > 0 && selectedDocuments.All(doc => doc != null))
                {
                    displayedFlowIndexPanel = new FlowIndexPanel(selectedDocuments, _workflowManager);

                    displayedFlowIndexPanel.CancelClickEvent += (s, e) => ClearLeftContentPlaceHolder();
                    displayedFlowIndexPanel.ValidateClickEvent += (sender, args) => notification.Execute(args);

                    AddControlToLeftContentPlaceHolder(displayedFlowIndexPanel);
                }
            }
        }

        private void UpdateFlowIndexPanelWithSelectedDocument()
        {
            if (displayedFlowIndexPanel != null)
            {
                List<Document> selectedDocuments = new List<Document>();
                if (DisplayMode == SelectModeDocument.Viewer)
                {
                    selectedDocuments.Add(CurrentDocument);
                }
                else
                {
                    selectedDocuments.AddRange(SelectedDocumentsFromThumbnails);
                }
                displayedFlowIndexPanel.m_oListSelectedFilename = selectedDocuments;
            }
        }

        private void AddControlToLeftContentPlaceHolder(UIElement control)
        {
            if (!LeftContentPlaceHolder.Children.Contains(control))
            {
                LeftContentPlaceHolder.Children.Clear();
                LeftContentPlaceHolder.Children.Add(control);
            }

            radOutlookBar.Visibility = Visibility.Collapsed;
            LeftContentPlaceHolder.Visibility = Visibility.Visible;
        }

        private void ClearLeftContentPlaceHolder()
        {
            displayedFlowIndexPanel = null;
            LeftContentPlaceHolder.Children.Clear();
            LeftContentPlaceHolder.Visibility = Visibility.Collapsed;
            radOutlookBar.Visibility = Visibility.Visible;
        }

        private void WorkflowManagerPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            OnPropertyChanged("WorkflowManager");
        }

        private void WorkflowManagerProcessed(object sender, ErrorEventArgs e)
        {
            CursorNormal(this);
        }

        private void WorkflowManagerProcessing(object sender, EventArgs e)
        {
            CursorWait(this);
        }

        #endregion

        #region Document & versioning informations

        /// <summary>
        /// Inits the command.
        /// </summary>
        private void InitCommand()
        {
            MakeToMajorCommand = new RelayCommand<VersionInformations.VersionSelectedEventArgs>(OnMakeToMajorActionPerformed);
            CheckOutCommand = new RelayCommand<VersionInformations.VersionSelectedEventArgs>(OnCheckOutActionPerformed);
            AddVersionCommand = new RelayCommand<RoutedEventArgs>(OnVersionAddedActionPerformed);
            VersionSelectedCommand = new RelayCommand<VersionInformations.VersionSelectedEventArgs>(OnVersionSelectedActionPerformed);
            DocumentUpdatingCommand = new RelayCommand<DocumentInformations.DocumentInformationEventArgs>(OnDocumentUpdatingActionPerformed);
            OpenCommentWindowCommand = new RelayCommand<bool>(OpenCommentWindow);
            OpenHistoricWindowCommand = new RelayCommand(OpenHistoricWindow);
        }

        /// <summary>
        /// Opens the historic window.
        /// </summary>
        private void OpenHistoricWindow()
        {
            FolderHistoricChildWindow folderHistoricChildWindow = new FolderHistoricChildWindow
            {
                FolderPageContext = this
            };
            folderHistoricChildWindow.Closed += FolderHistoricChildWindowClosed;
            folderHistoricChildWindow.ShowDialog();
        }

        /// <summary>
        /// Folders the historic child window closed.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="Telerik.Windows.Controls.WindowClosedEventArgs" /> instance containing the event data.</param>
        private void FolderHistoricChildWindowClosed(object sender, WindowClosedEventArgs e)
        {
            FolderHistoricChildWindow folderHistoricChildWindow = sender as FolderHistoricChildWindow;
            folderHistoricChildWindow.Closed -= FolderHistoricChildWindowClosed;
        }

        /// <summary>
        /// Raises the <see cref="E:VersionAddedActionPerformed"/> event.
        /// </summary>
        /// <param name="args">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void OnVersionAddedActionPerformed(RoutedEventArgs args)
        {
            CreateNewVersionClick();
        }

        /// <summary>
        /// Raises the <see cref="E:MakeToMajorActionPerformed"/> event.
        /// </summary>
        /// <param name="args">The <see cref="Rio.Framework.Pages.Controls.VersionInformations.VersionSelectedEventArgs"/> instance containing the event data.</param>
        private void OnMakeToMajorActionPerformed(VersionInformations.VersionSelectedEventArgs args)
        {
            MakeThisVersionToMajorClick(args.SelectedVersion);
        }

        /// <summary>
        /// Raises the <see cref="E:MakeToMajorActionPerformed"/> event.
        /// </summary>
        /// <param name="args">The <see cref="Rio.Framework.Pages.Controls.VersionInformations.VersionSelectedEventArgs"/> instance containing the event data.</param>
        private void OnCheckOutActionPerformed(VersionInformations.VersionSelectedEventArgs args)
        {
            CheckOutClick(args.SelectedVersion);
        }

        /// <summary>
        /// Raises the <see cref="E:VersionSelectedActionPerformed"/> event.
        /// </summary>
        /// <param name="args">The <see cref="Rio.Framework.Pages.Controls.VersionInformations.VersionSelectedEventArgs"/> instance containing the event data.</param>
        private void OnVersionSelectedActionPerformed(VersionInformations.VersionSelectedEventArgs args)
        {
            LoadSelectedVersion();
        }

        /// <summary>
        /// Raises the <see cref="E:DocumentUpdatingActionPerformed"/> event.
        /// </summary>
        /// <param name="args">The <see cref="Rio.Framework.Pages.Controls.DocumentInformations.DocumentInformationEventArgs"/> instance containing the event data.</param>
        private void OnDocumentUpdatingActionPerformed(DocumentInformations.DocumentInformationEventArgs args)
        {
            UpdateDocument(args.Note, args.Author, args.CreditPhoto);

            if (args.Author.Equals(String.Empty) && args.Note.Equals(String.Empty) && args.CreditPhoto.Equals(String.Empty))
            {
                UpdateDocumentBarItemStyle(false);
            }
            else
            {
                UpdateDocumentBarItemStyle(true);
            }
        }

        /// <summary>
        /// Updates the document bar item style.
        /// </summary>
        /// <param name="containsData">The contains data.</param>
        private void UpdateDocumentBarItemStyle(bool containsData)
        {
            Brush backgroundBrush;

            if (containsData)
            {
                backgroundBrush = Resources["DocumentBarItem_Background_WithData"] as LinearGradientBrush;
            }
            else
            {
                //use the background of an other item to keep the same theme
                backgroundBrush = indexBarItem.Background;
            }

            documentBarItem.Background = backgroundBrush;
        }
        #endregion

        #region Drag'n Drop between ListVignetteSearch and TreeView Items

        private void OnDocumentsToItemDragQuery(object sender, DragDropQueryEventArgs e)
        {
            if (sender is ListVignetteSearch)
            {
                ListVignetteSearch listVignetteSearchSource = sender as ListVignetteSearch;

                e.Options.Payload =
                    (listVignetteSearchSource.ListBoxVignette.SelectedItems as ObservableCollection<object>).Cast
                        <ImageRioSearch>().ToList();
            }
            else if (sender is RadGridView)
            {
                RadGridView radGridViewSource = sender as RadGridView;

                e.Options.Payload = new DragDropOperation { Payload = radGridViewSource.SelectedItems.Cast<ImageRioSearch>().ToList() };
            }

            if (!e.Options.ParticipatingVisualRoots.Contains(this))
            {
                e.Options.ParticipatingVisualRoots.Add(this);
            }

            e.QueryResult = true;
            e.Handled = true;
        }

        private void OnDocumentsToItemDropQuery(object sender, DragDropQueryEventArgs e)
        {
            e.QueryResult = true;
            e.Handled = true;
        }

        private void OnDocumentsToItemDropInfo(object sender, DragDropEventArgs e)
        {
            TreeViewDragCue cue = e.Options.DragCue as TreeViewDragCue;
            if (cue != null)
            {
                cue.DragActionContent = null;
                cue.IsDropPossible = false;
            }

            if (!(e.Options.Destination is RadTreeViewItem))
                return;

            if (e.Options.Source.GetType() == e.Options.Destination.GetType())
                return;

            if (e.Options.Payload == null)
                return;

            DragDropOperation dragDropOperation = e.Options.Payload as DragDropOperation;

            if (dragDropOperation == null)
                return;

            if (dragDropOperation.Payload == null)
                return;

            if (!(dragDropOperation.Payload is List<ImageRioSearch>))
                return;

            if (cue != null)
            {
                (e.Options.Destination as RadTreeViewItem).IsSelected = true;

                var item = (e.Options.Destination as RadTreeViewItem).DataContext as DataItemTreeView;

                if (item != null
                    && !item.IsTrashItem
                    && CurrentDocument != null && !CurrentDocument.Deleted)
                {
                    cue.DragActionContent = String.Format(Resx.GetLabel("ClassifiedIn"),
                                                          item.OriginalName);
                    cue.IsDropPossible = true;

                    e.Handled = true;
                }
                else
                {

                    if (item != null && !item.IsTrashItem)
                    {
                        bool result = false;
                        if ((SelectedDocumentsFromThumbnails != null) && (SelectedDocumentsFromThumbnails.Count > 0) &&
                            (DisplayMode == SelectModeDocument.Thumbnail || DisplayMode == SelectModeDocument.List))
                        {
                            foreach (var document in SelectedDocumentsFromThumbnails)
                            {
                                if (document != null && !document.Deleted)
                                {
                                    result |= true;
                                }
                                else
                                {
                                    result = false;
                                }
                            }
                        }

                        if (result)
                        {
                            cue.DragActionContent = String.Format(Resx.GetLabel("ClassifiedIn"),
                                                                  item.OriginalName);
                            cue.IsDropPossible = true;
                        }
                        e.Handled = true;
                    }
                }

                if (e.Options.Status == DragStatus.DropComplete && cue.IsDropPossible)
                {
                    MessageBoxChildWindow errorMessage = new MessageBoxChildWindow(String.Empty, String.Format(Resx.GetLabel(ResxCommon.DRAG_AND_DROP_CLASSIFIED_NOTIFICATION), item.OriginalName), MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                    errorMessage.Closed += (s, e1) =>
                                               {
                                                   if (errorMessage.DialogResult == true)
                                                   {
                                                       SelectedItem = item;

                                                       UpdateDocumentItem();
                                                   }
                                               };
                    errorMessage.ShowDialog();

                    e.Handled = true;
                }

            }
        }

        private void OnDocumentsToItemDragInfo(object sender, DragDropEventArgs e)
        {
            if (sender is ListVignetteSearch || sender is RadGridView)
            {
                if (e.Options.Status == DragStatus.DragInProgress)
                {
                    TreeViewDragCue cue = new TreeViewDragCue
                                              {
                                                  DisplayMemberPath = "OriginalName"
                                              };

                    if (sender is ListVignetteSearch)
                    {
                        ListVignetteSearch listVignetteSearchSource = sender as ListVignetteSearch;

                        cue.ItemsSource =
                            (listVignetteSearchSource.ListBoxVignette.SelectedItems as ObservableCollection<object>).
                                Cast<ImageRioSearch>().ToList();
                    }
                    else
                    {
                        RadGridView radGridViewSource = sender as RadGridView;

                        cue.ItemsSource = radGridViewSource.SelectedItems.Cast<ImageRioSearch>().ToList();
                    }

                    e.Options.DragCue = cue;

                    e.Handled = true;
                }
            }
        }

        #endregion
    }

    #region Converters

    public class ManageWorkflowToolBarVisibility : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            WorkflowManager manager = value as WorkflowManager;

            if (manager == null)
                return Visibility.Collapsed;

            if (manager.WorkflowInstance == null)
                return Visibility.Collapsed;

            return Visibility.Visible;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

    public class DocumentNameToOutlookBarItem : FrameworkElement, IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            Document doc = value as Document;

            if (doc != null)
                return doc.GetCurrentVersion() != null ?
                    String.Format("{0}(v{1}){2}", Resx.GetLabel(ResxCommon.DOCUMENT_LABEL), doc.GetCurrentVersion().FullVersion, doc.OriginalNameFile)
                    : String.Format("{0}{1}", Resx.GetLabel(ResxCommon.DOCUMENT_LABEL), doc.OriginalNameFile);

            return value;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }


    #endregion
}
